Entity Framework
Entity Framework
Querying
EF API translates LINQ-to-Entities queries to SQL queries for
relational databases using EDM and also converts results back to
entity objects.
Entity Data Model
Saving
EF API infers INSERT, UPDATE, and DELETE commands based
on the state of entities when the SaveChanges() method is called.
The Change Track keeps track of the states of each entity or
object as and when an action is performed.
Context Class in Entity Framework
It represent a session with the underlying database using which you can
perform CRUD (Create, Read, Update, Delete) operations.
It has Method like saveChanges() and Entry() to check the object state.
Context Class in Entity Framework
DbContext is the primary class that is responsible for interacting with
the database. It is responsible for the following activities:
Querying: Converts LINQ-to-Entities queries to SQL query and sends them to the
database.
Change Tracking: Keeps track of changes that occurred on the entities after querying
from the database.
Persisting Data: Performs the Insert, Update and Delete operations to the database,
based on entity states.
Caching: Provides first level caching by default. It stores the entities which have been
retrieved during the life time of a context class.
Manage Relationship: Manages relationships one to one, one to many and many to
many relationship.
Context Class in Entity Framework
DbContext represents a session with the database and can be
used to query and save instances of your entities.
DbContext perform :
1. Manage Database Connection
2. Configure Model and Relationship
3. Querying Database
4. Saving Data to the Database
5. Configure Change Tracking
Dbset Class in Entity Framework
The context class (derived from DbContext) must include
the DbSet type properties for the entities which map to database
tables and views.
FindAsync: Asynchronous method for finding an entity with the given primary key
values.
Remove:It sets the Deleted state to the specified entity, which will delete the data when
SaveChanges() is called.
RemoveRange: Sets Deleted state to a collection of entities that will delete the data in a
single DB round trip when SaveChanges() is called.
} // Entities
EF API will create the Students and Grades tables in the database,
as shown below
Enityt properties
An Entity has two properties
1. Scalar Property
• Each scalar property maps to a column in the database table which stores an
actual data.
// scalar properties
EF API does not create any column for the collection navigation
property in the related table of an entity.
Values are :
1. Added
2. Modified
3. Deleted
4. Unchanged
Entity State in Entity Framework
The Context holds the reference to all the entity objects as soon as
retrieved from the database.
The change in entity state from the Unchanged to the Modified state is the
only state that's automatically handled by the context. All other changes
must be made explicitly using proper methods of DbContext or DbSet.
EF API builds and executes the INSERT, UPDATE, and DELETE commands
based on the state of an entity when the context.SaveChanges()
method is called.
I. It executes the INSERT command for the entities with Added state.
II. It executes the UPDATE command for the entities with Modified state.
EntityState in Entity Framework
The context does not track entities in the Detached
state.
The property values of the entity have not been modified since
it was retrieved from the database.
context.Entry(firstProduct).State = EntityState.Detached;
context.SaveChanges();
Added State
Added entity state indicates that the entity exists in the
context, but does not exist in the database.
The Modified entity state indicates that the entity is modified but not
updated in the database.
context.SaveChanges();
what is the state of the object ?
Deleted State
Whenever we call the Remove method, the entity will be removed from the
context and will be marked as a “Deleted” state.
When the SaveChanges method is called, the corresponding rows are deleted
from the database.
The Deleted entity state indicates that the entity is marked for deletion, but not yet
deleted from the database. It also indicates that the entity exists in the database.
TheDbContext generates the DELETE SQL Query to remove the entity from the
database.
The entity is removed from the context once the delete operation succeeds after
the saveChanges.
Deleted State
Product firstProduct = context.Products.Find(1);
what is the state of the object ?
Context. Products.Remove(firstProduct);
what is the state of the object ?
context.SaveChanges();
Note: The point that you need to remember is Entity Framework builds
and executes the INSERT, UPDATE, and DELETE commands based on
the state of an entity when the context.SaveChanges() method is called.
Development Approaches with Entity
Framework
There are different approaches you can use
while developing your application using Entity
Framework:
1.Database-First
2.Code-First
Code-First Approach
Use this approach when you do not have an existing
database for your application.
}
Create Context Class
Inherit from DbContext class and uses the DbSet property
which is a collection of Our Domain Class.
StudentName = "Bill"
};
ctx.Students.Add(stud);
ctx.SaveChanges();
}
}
Data Annotations Attributes
Data Annotations attributes are .NET attributes
which can be applied on an entity class or properties
to override default conventions in EF 6.
Tables, Columns, ……
Table Attribute
using System.ComponentModel.DataAnnotations.Schema; [Table("StudentMaster")]
public class Student
{
Check it on reference
Enable migrations
The Entity Framework DbSet
The DbSet<TEntity> class represents a collection for a given entity within the model and is the
gateway to database operations against an entity. DbSet<TEntity> classes are added as properties to
the DbContext and are mapped by default to database tables that take the name of
the DbSet<TEntity> property.
The second DbSet property represents a collection of Author objects, and is mapped to a
table named "Authors".
Basic operations :
DbSet objects represent collections of entities in memory. Any changes you make to the
contents of a DbSet will only be committed to the database if the SaveChanges()
method of the DbContext is called.
The DbSet class exposes a number of methods that enable you to perform basic CRUD
(Create, Read, Update, Delete) operations against entities.
Adding an entity
To add an new entity to the collection represented
by the DbSet Use DbSet.Add() Method
Example :
}
}
Retrieving an entity
A convenience method called Find is available which is used to query the
context for an entity by primary key value:
}
}
The most commonly method used to return multiple entities is the ToList method:
4. Creating Database
Create the database using the update-database -verbose
command in the Package Manager Console.
4. Enable Migrations : PM> Enable-Migrations
Base on the code we develop we have to make changes to our database.
5. Create your domain and then add this class to your dbContext class.
we need to tell Enitity Framework that we want this classto be repilicated
to our DB and come under control of EF. Example if our class name is User
class urDBContext
{
public DbSet Users{ get; set; }
}
6. Migrate to DB
PM> add-migration addUser
7. bbn