0% found this document useful (0 votes)
23 views37 pages

Object Relational Mapping

This document provides an overview of CRUD operations using Entity Framework, detailing how to create, read, update, and delete records in a database context. It explains the roles of DbSet<T> and EntityState in managing entities and their states during these operations. The document also includes practical examples of implementing these operations in code, highlighting the efficiency of Entity Framework compared to ADO.NET.

Uploaded by

bperson534
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views37 pages

Object Relational Mapping

This document provides an overview of CRUD operations using Entity Framework, detailing how to create, read, update, and delete records in a database context. It explains the roles of DbSet<T> and EntityState in managing entities and their states during these operations. The document also includes practical examples of implementing these operations in code, highlighting the efficiency of Entity Framework compared to ADO.NET.

Uploaded by

bperson534
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Object Relational Mapping

(ORM)
Lecture 03
CRUD Operations

EntityState. Added EntityState.Modified EntityState.Deleted


What Entity Framework do?

● It will generate respective sequential command


● Save changes > Insert command
● Modified and save > Update command
● Delete and save > ?
● When you want to read a data from the database what will you
use ?
Select command > L2E query (Link to Entity) >
Language integrated query
Create Operation

● In Entity Framework, DbSet<T> represents a collection of


entities of a specific type T within a database context,
typically derived from DbContext.

● DbSet.Add method allows you to add a new entity to this


context , which will insert a new record to the database
when you call the SaveChanges() method on the database
context.
Here's a step-by-step explanation of how this works:
Creating an Entity Instance:

● First, you create an instance of the entity you want to add to the database. This entity should correspond to
the type T of the DbSet<T> collection.
● For example, if you have a Blog entity and a corresponding Blogs DbSet in your DbContext, you would create
a new Blog instance.

Adding the Entity to DbSet:

● Once you have the entity instance, you use the Add method of the DbSet<T> collection to add it to the
context.
● This operation adds the entity to the in-memory collection managed by Entity Framework, marking it as an
entity to be inserted into the database when SaveChanges() is called.

Save Changes to Database:

● After adding all the entities you want to persist, you call the SaveChanges() method on the database context.
● Entity Framework then generates and executes SQL commands necessary to insert the new entity into the
database.
● The entity is added to the appropriate database table, and if successful, the changes are committed to the
database.
Update Operation

● EF API keeps track of all the entities retrieved using a context.

● Therefore, when you edit entity data, EF automatically marks


EntityState to Modified,Which results in an update statement in
the database when you call the SaveChanges() Method.
Here's how the process works when editing entity data:
Entity Retrieval and Tracking:

● When you retrieve entities from the database using EF, such as through LINQ queries or navigation properties,
EF automatically tracks these entities.
● Each entity is associated with its own state, known as EntityState, which indicates whether the entity is Added,
Modified, Deleted, or Unchanged.

Editing Entity Data:

● When you modify the properties of an entity that is being tracked by EF, EF automatically marks the EntityState
of that entity as Modified.
● This automatic change tracking allows EF to keep track of the changes made to the entity's properties without
any explicit intervention from the developer.

Save Changes to Database:

● After making modifications to one or more entities, you call the SaveChanges() method on the DbContext to
persist these changes to the database.
● EF generates and executes the necessary SQL commands, including UPDATE statements, to update the
corresponding records in the database based on the modified entities.
● Only the properties that have been modified are included in the UPDATE statement, resulting in efficient
database updates.
Delete Operation

Use the DbSet.Remove() method to delete a record in the database table

Read Operation
When using Entity Framework (EF), the DbSet class represents a
collection of entities within a database context, and it is indeed derived
from IQueryable.
This allows you to use LINQ (Language-Integrated Query) to query
against DbSet, which is then translated into SQL queries by the EF API to
interact with the underlying database.
Search Operation

We can use the Find() method of DbSet to Search the entity based on the
primary key value.
Lets’ see those in practical…….
Now you are at this stage…,
Next move into database first,
Select Cities table > Edit rows
> Add Two cities with city id 1
and 2 > save the changes.

Lets’ keep AreaId as Identity


column and perform CRUD
operation on other three.

Since CityId is a FK, We need


to set Area table CityId as 1
and 2 only.
Go to Visual studio,
1. Create a class > CRUD.cs
Basic code for the class as follows
Create object of the context class and Area class
<Entity Name> db = new <Entity Name>(); //object of the context class

Area areaObj = new Area(); //Area object class


Let’s handle case 1
case 1: //Add new record

Console.WriteLine("Enter Area Name,CityId and Pincode"); //accepting data from


the user by giving the message

areaObj.AreaName = Console.ReadLine();

areaObj.CityId=Convert.ToInt32(Console.ReadLine());

areaObj.Pincode= Console.ReadLine();
Next, We have to specify our context class object
DbSet property that declared in our context class

1. Here is the DbSet property declared in our context class > Areas (Which is
type DbSet)

2. Use following code to specify the context class

db.Areas.Add(areaObj); //add method to accepting object of a area entity

db.SaveChanges(); //To save the changes in the database


Then, Automatically insert command will generate and execute by EF

In ADO.NET we have to write lots of codes and we have to use terms


related to our database

Here in EF, totally working with C# classes only


Let’s move into the case 2 : Read all records
If you write db.areas it will give all area that are stored in your database

So we can use as follows to read records,

case 2://Read all records

foreach (Area a in db.Areas) //Areas is our DbSet property which is in our context class & db is our
object in our context class created above

Console.WriteLine("{0}\t{1}\t{2}\t{3}",a.AreaId,a.AreaName,a.Pincode,a.City.CityName); //display
areas

break;
Suppose you want to display CityName,

● But there is no city name property in


the Area table
● You have City, which is navigation
property (It created automatically
when we use database first
approach)
● So you can go through like below to
access the CityName in City Table

a.City.CityName
Let’s run this part and confirm whether its working fine…
1. Go to Project > Database first properties > Specify the startup object >
CRUD> Save
2. Run the project…
3. Give option 1

4. Add values accordingly

5. Hit enter > it will take time bcz it is adding data to your database

6. Add another value as above

7. Now view the results by using option 2


Here City Name print by
using the navigation
property.
Let’s look
how
database
updated
>
We have remain two operations Update record & Delete record….

1. First you have to declare an id to define AreaId which is type integer.


2. Then display message
Console.WriteLine("Enter Area Id to update: ");
id = Convert.ToInt32(Console.ReadLine()); //input id
3. Find the Area Id using Find method in our DbSet class, find method
will find the record based on your primary key that you have provided and
it will return that entity, so I collect that entity in our "areaObj" object that
declared in the class above
areaObj = db.Areas.Find(id);
4. Particular Area can be not found and in that case it will return null
if (areaObj == null)
Console.WriteLine("Invalid Area Id, Try again! ");

else //Otherwise accept the user updated values


{
Console.WriteLine("Enter Modified Area name, City id, and PinCode");
areaObj.AreaName = Console.ReadLine();
areaObj.CityId = Convert.ToInt32(Console.ReadLine());
areaObj.Pincode = Console.ReadLine();
db.SaveChanges();
}
Delete Operation
Console.WriteLine("Enter Area Id to Delete ");
id = Convert.ToInt32(Console.ReadLine()); //input id
Find the Area Id using Find method in our DbSet class, find method will
find the record based on your primary key that you have provided and it
will return that entity ,so I collect that entity in our "areaObj" object that
declared in above
areaObj = db.Areas.Find(id);
Particular Area can be not found and in that case it will return null
if (areaObj == null)
Console.WriteLine("Invalid Area Id, Try again! ");

else
{
Remove area object from the database. Here remove method is called it will mark as
Entity state is deleted.
db.Areas.Remove(areaObj);
db.SaveChanges(); //Delete sql querry will be executed in the
database
}
First display the available data and check the database
Finally play with Records and check how database is
updating………..

You can see that we have to write less code and it is


easy to perform CRUD operation using entity
framework as compared to ADO.NET code.

Developers productivity will increase


What you should able to know after this lecture?

How to perform CRUD operations on Entity


Framework ?

You might also like