You are on page 1of 70

Entity framework

Entity Framework Code First Approach


What is Entity Framework?
Developers often used to write ADO.NET code to save or
retrieve application data from the underlying database.

We used to open a connection to the database, create a


DataSet to fetch or submit the data to the database,
convert data from the DataSet to .NET objects or vice-
versa to apply business rules.

This was a cumbersome or bulky and error prone process.

So what is the solution ?


Entity Framework
Automate all these database related activities for your
application.

Itenables developers to work with data using objects of


domain specific classes (Model) without focusing on the
underlying database tables and columns where this
data is stored.

Entity Framework is an object-relational mapper (ORM).

 Iteliminates the need for most of the data-access code


that developers usually need to write.
Entity Framework
What is ORM?
The term ORM stands for Object-Relational Mapper, and
it automatically creates classes based on database tables
and vice versa is also true. It can also generate the
necessary SQL to create the database based on the classes.

 ORM Framework generates the necessary SQL (to


perform the CRUD operation) that the underlying database
can understand. So, in simple words, we can say that the
ORM Framework eliminates the need for most of the data
access code that, as a developer, we generally write.
Entity Framework
 Entity Framework fits between the business entities (domain
classes) and the database.

 It saves data stored in the properties of business entities


and also retrieves data from the database and converts it to
business entities objects automatically.
Basic Workflow in Entity Framework
Entity framework work flow
1.First
of all, you need to define your model. Defining the model includes
defining your domain classes, context class derived from DbContext, and
configurations. EF will perform CRUD operations based on your model.

2.Toinsert data, add a domain object to a context and call


the SaveChanges() method. EF API will build an appropriate INSERT
command and execute it to the database.

3.Toread data, execute the LINQ-to-Entities query in your preferred


language (C#/VB.NET). EF API will convert this query into SQL query for
the underlying relational database and execute it. The result will be
transformed into domain (entity) objects and displayed on the UI.

4.Toupdate or delete data, update or remove entity objects from a context


and call the  SaveChanges()  method. EF API will build the appropriate
UPDATE or DELETE command and execute it to the database.
How Entity Framework Works?

Entity Framework API (EF6 & EF Core) includes the ability to map
domain (entity) classes to the database schema.

Translate LINQ queries to SQL and then Execute.

Track changes occurred on entities during their lifetime.

Save changes to the database based on state of the object.


Entity Data Model

EDM is an in-memory representation of the entire metadata:


conceptual model, storage model, and mapping between them.
Entity Data Model
Conceptual Model: EF builds the conceptual model from your
domain classes, context class, default conventions followed in
your domain classes, and configurations.

Storage Model: EF builds the storage model for the underlying


database schema. In the code-first approach, this will be inferred
from the conceptual model. In the database-first approach, this
will be inferred from the targeted database.

Mappings: EF includes mapping information on how the


conceptual model maps to the database schema (storage model).
Entity Data Model
EF performs CRUD operations using this EDM. It uses EDM in
building SQL queries from LINQ queries, building INSERT, UPDATE,
and DELETE commands, and transform database result into entity
objects.

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.

The context class in Entity Framework is a class which derives (inherit)


from System.Data.Entity.DbContext.

The context class is used to query or save data to the database.

It is a bridge between your domain or entity classes and the database.

DbContext instance is the primary class that is responsible for interacting


with the database and performing the database CRUD Operations. 

It has Method like saveChanges() and Entry() to check the object state.

Example : context.Entry(student).State
Context Class in Entity Framework
DbContextis the primary class that is responsible for interacting with
the database. It is responsible for the following activities:

Manage Database Connection : EF is built on top of ADO.Net.

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.

Object Materialization: Converts raw data from the database into entity objects.
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 can be considered as Repository patterns.

 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.

Methods of DbSet Class


1. DbSet Add Method 
 used to add the given entity to the context object with the Added
State. 

 when we call the SaveChanges method, the entity which is in the


Added state is inserted into the corresponding database table which
is mapped with the given entity.

 Then the object state or entity state is moved from Added to Unchanged
State.
Dbset Class in Entity Framework
 Add: Adds a new entity to DbContext with Added state and starts tracking
it.

This new entity data will be inserted into the database when SaveChanges() is
called.

AddAsync: Asynchronous method for adding a new entity to DbContext


with Added state and starts tracking it.

Thisnew entity data will be inserted into the database when


SaveChangesAsync() is called.
Dbset Class in Entity Framework
AddRange: Adds a collection of new entities to DbContext with Added
state and starts tracking it. This new entity data will be inserted into the
database when SaveChanges() is called.

AddRangeAsync: Asynchronous method for adding a collection of new


entities, which will be saved on SaveChangesAsync().

Attach: Attaches a new or existing entity to DbContext with an


Unchanged state and starts tracking it.

AttachRange: Attaches a collection of new or existing entities to


DbContext with an Unchanged state and starts tracking it.
Dbset Class in Entity Framework
Entry: Gets an EntityEntry for the given entity. The entry provides access to change
tracking information and operations for the entity.

Find: Finds an entity with the given primary key values.

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.

SaveChanges: Execute INSERT, UPDATE, or DELETE commands to the database for the


entities with Added, Modified, or Deleted state.
Dbset Class in Entity Framework
SaveChangesAsync: Asynchronous method of SaveChanges()

Set: Creates a DbSet<TEntity> that can be used to query and save


instances of TEntity.

Update: Attaches disconnected entity with Modified state and


starts tracking it. The data will be saved when SaveChagnes() is
called.

UpdateRange: Attaches a collection of disconnected entities with


a Modified state and starts tracking it. The data will be saved
when SaveChagnes() is called.
Dbset Class in Entity Framework
 OnConfiguring: Override this method to configure the
database (and other options) to be used for this context.

This method is called for each instance of the context


that is created.

OnModelCreating: Override this method to configure


further the model discovered by convention from the
entity types exposed in DbSet<TEntity> properties on
your derived context.
Dbset Class in Entity Framework
Example :
var student = new Student
{
FirstName = “Mira",
LastName = “Sas",
StandardId = 1
};
//Adding new student to the context object
context.Students.Add(student);
//Now the Entity State will be in Added State
Console.WriteLine("Before SaveChanges Entity State: "+context.Entry(student).State);
context.SaveChanges();
// the entity state will changed to Unchanged
Console.WriteLine("Before SaveChanges Entity State: "+context.Entry(student).State);
Sample class
using System.Data.Entity;
public class SchoolContext : DbContext
{
public SchoolContext() {

} // Entities

public DbSet<Student> Students { get; set; }

public DbSet<StudentAddress> StudentAddresses { get; set; }


}
What is an Entity in Entity Framework?
An entity in Entity Framework is a class that maps to a
database table.

This class must be included as a DbSet<TEntity> 


type property in the DbContext class in order to map to the
database tables.
EF API maps each entity to a table and each property of an
entity to a column in the database.

For example, the following Student, and Grade are domain


classes in the school application.
Framework is an improvement to ADO.NET, which automates
the process of accessing and storing data in databases.
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
public Grade Grade { get; set; }
}
public class Grade
{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
public List<Student> Students { get; set; }
}
What is an Entity in Entity Framework?
The Student, and Grade are 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.

public class Student


{
//scalar properties
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public byte[] Photo { get; set; }

//reference navigation properties


public Grade Grade { get; set; }
}
EF API will create a column in the database table for each
scalar property, as shown below.
2. Navigation Property

The navigation property represents a relationship to another entity.

There are two types of navigation properties: Reference


Navigation(One) and Collection Navigation(Many).

1. Reference Navigation Property


 If an entity includes a property of type another entity type, it is
called a Reference Navigation Property. It points to a single entity
and represents multiplicity of one (1) in the entity relationships.

EF API will create a ForeignKey column in the table for the
navigation properties that points to a PrimaryKey of another table
in the database.
Example :
public class Student {

// scalar properties

public int StudentID { get; set; }

public string StudentName { get; set; }

public DateTime? DateOfBirth { get; set; }

public byte[] Photo { get; set; }


//reference navigation property

public Grade Grade { get; set; }


}
2. Collection Navigation Property

If an entity includes a property of generic collection of an entity type, it


is called a collection navigation property. It represents multiplicity of
many.

EF API does not create any column for the collection navigation property
in the related table of an entity.

But it creates a column in the table of an entity of generic collection.

For example, the following Grade entity contains a generic collection


navigation property List<Student>.

So EF API will create a column Grade_GradeId in the Students table in


the database.
Entity State in Entity Framework
EF API maintains the state of each entity during its lifetime.

Each entity has a state based on the operation performed on it via


the context class.

Theentity state represented by an enum 


System.Data.Entity.EntityState

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.

keeps track of entity states and maintains modifications made to the


properties of the entity. This feature is known as Change Tracking.

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.
III.It executes the DELETE command for the entities in Deleted state.
EntityState in Entity Framework
The context does not track entities in the Detached state.

The following figure illustrates the significance of entity


states:
Entity State
The Context object holds the reference to all the entity
objects as soon as retrieved from the database.

 The Context object keeps track of entity states and


maintains modifications made to the properties of the
entity.

The above feature is known as Change Tracking.


Unchanged State 

The property values of the entity have not been modified since it
was retrieved from the database.

The Object value in memory == row value in the storage

SaveChanges ignores this entity. 

Product firstProduct = context.Products.Find(1);


//state ?
context.SaveChanges();
//state ?
Attaching an Existing Entity  
Ifyou have an entity that you already know exists in the database but which is
not currently being tracked by the context then you can tell the context to track
the entity using the Attach method on DbSet.

The entity will be in the Unchanged state in the context.

Product ExistingProduct = new Product()


{
ID = 1,
Name = "IT"
};
context.Products.Attach(ExistingProduct);
ExistingProduct.State = EntityState.Modified;
context.SaveChanges();
Detached State
 We can change the Entity State to the Detached state by using the Entity
State property.

 Once the entity is in the Detached state, it cannot be tracked by the


Context object.

Product firstProduct = context.Products.Find(1);

context.Entry(firstProduct).State = EntityState.Detached;

firstProduct.description= “Product description";

context.SaveChanges();
Added State
Added entity state indicates that the entity exists in the
context, but does not exist in the database.

DbContext generates the INSERT SQL query and inserts the


data into the database when the SaveChanges method is
invoked.

Once the SaveChanges method execution is successful, the


state of the Entity is changed to an Unchanged state.
Added State
Product newProduct = new Product ()
{
Name = "Sales",
Location = “Addis Ababa"
};

//Now context object tracking the entity state


context.products.Add(newProduct );
//what is state of the obj ?
context.SaveChanges();
//what is state of the obj ?
Modified State

 The entity will be in a Modified state whenever we modify scalar


properties.

The Modified entity state indicates that the entity is modified but not
updated in the database.

It also indicates that the entity exists in the database.

The Dbcontext generates the UPDATE SQL Query to update the entity
in the database.

Once the saveChanges is successful the state of the entity is changed to


Unchanged. 
Modified State

 Product firstProduct = context.Products.Find(1);


what is the state of the object ?

firstProduct.Location = “Addis Ababa";


what is the state of the object ?

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.

The DbContext 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();
what is the state of the object ?

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.

you start writing your entities (domain classes) and


context class first and then create the database from these
classes using migration commands.

DDD : Domain Driven Design


EF Code-First Example
 Let Us Create our Domain Class
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
public Grade Grade { get; set; }
}

public class Grade


{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section{get;set; }
public ICollection<Student>Students { get; set;}

}
Create Context Class
Inherit from DbContext class and uses the DbSet property
which is a collection of Our Domain Class.

public class SchoolContext: DbContext


{
public DbSet<Student> Students { get; set; }

public DbSet<Grade> Grades { get; set; }


}
Add Student Object
static void Main(string[] args)
{

using (var ctx = new SchoolContext())

Student stud = new Student()

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
{

public int StudentID { get; set; }

public string StudentName { get; set; }


}
Relation ship One to One
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual StudentAddress Address { get; set; }
}

public class StudentAddress


{
[ForeignKey("Student")]
public int StudentAddressId { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public int Zipcode { get; set; }
public string State { get; set; }
public string Country { get; set; }
public virtual Student Student { get; set; }
}
One TO Many

public class Student


{
public int StudentId { get; set; }
public string StudentName { get; set; }
}

public class Grade


{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
public List<Student> Students { get; set; }
}
Many to Many
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual List<Course> Courses { get; set; }
}

public class Course


{
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual List<Student> Students { get; set; }
}
Summary Note :
Install EntityFramework

Nuget Package Manager

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.

Step 1 … Create Your Model Class


public class Author
{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Book> Books { get; set; }
}

public class Book


{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public int AuthorId { get; set; }
}
The Entity Framework DbSet
Step 2 Creating Context Class
public class SampleContext : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
}

Step 3 Configuring App.Config File


<connectionStrings>
<add name=" SampleContext "
connectionString="server=.; database=DBName; Integrated security=true;"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
The Entity Framework DbSet
 In the example above, two DbSet<TEntity> properties have been added to
the DbContext class.

 The first represents a collection of Book objects, which is mapped by convention to a


database table named "Books", after the property name.

 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 :

var author = new Author{


FirstName = "William",
LastName = "Shakespeare"
};
using (var context = new SampleContext())
{
context.Authors.Add(author); // adds the author to the DbSet in memory
context.SaveChanges(); // commits the changes to the database
}
Retrieving an entity
 If you wish to retrieve a single instance of an entity, you can use
the First or Single method depending on whether you expect there to be more than
one row matching the criteria.
 The Single method will result in an exception being raised if more than one matching
row exists. It should only be used when querying the context for entities by a unique
key:

using (var context = new SampleContext())


{
// Use it with try catch block
var author = context.Authors.Single(a => a.AuthorId == 1);
}
Retrieving an entity
 If you are not certain of retrieving any data based on the criteria you pass in, you
should use the FirstOrDefault or SingleOrDefault methods, which return null in the event that
no rows match the search criteria:

using (var context = new SampleContext())


{
var author = context.Authors.Single(a => a.AuthorId == 1);
if(author!=null)
{

}
}
Retrieving an entity
A convenience method called Find is available which is used to query the
context for an entity by primary key value:

using (var context = new SampleContext())


{
var author = context.Authors.Find(1);
if(author!=null)
{

}
}

The most commonly method used to return multiple entities is the  ToList method:

using (var context = new SampleContext())


{
var author = context.Authors.ToList();
}
Modifying an entity
◦ To update an entity, make the required changes to the value of
the property or properties and call SaveChanges() method

◦ The entity must be tracked by the context to be updated.

using(var context = new SampleContext())


{
var author = context.Authors.Find(1); // retrieve the entity
author.LastName = “Mr. Xxxx"; // State become modified
context.SaveChanges(); // Update query --- commit the changes
}
Deleting an entity
◦ Use DbSet.Remove() method is used to delete an entity.
The entity must be tracked by the context to be
removed:

using(var context = new SampleContext())


{
var author = context.Authors.Find(1);
If(author!=null)
{
context.Authors.Remove(author); //deletion state
context.SaveChanges();
}
}
Relationship
One To Many
public class Author
{
//scalar pro.
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
//col navigational pro.
public List<Book> Books { get; set; }
}

public class Book


{
public int BookId { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
Relationship
Many To Many
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public List<Category> Categories { get; set; }
}

public class Category


{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public List<Book> Books { get; set; }
}
Relationship
One to One

public class Author


{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AuthorBiography Biography { get; set; }
}
public class AuthorBiography
{
public int AuthorBiographyId { get; set; }
public string Biography { get; set; }
public DateTime DateOfBirth { get; set; }
public string PlaceOfBirth { get; set; }
public string Nationality { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
Step by step
1. Install Entity Framework on your project.
 Microsoft.EntityFrameworkCore.SqlServer package
 Microsoft.EntityFrameworkCore.Tools package

2. Create Your DBContext Class


Step by step
public class EFCoreDbContext : DbContext
{
public EFCoreDbContext()
{
}
//OnConfiguring() method is used to select and configure the data source
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=pcName;Database=DBNm;
Trusted_Connection=True; TrustServerCertificate=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//use this to configure the model
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
Step by step
3. Open the Package Manager Console.
 Type the add-migration CreateEFCoreDB1 command,
 Select the project where your Context class is,
 Press the enter button
 It will create a new folder named Migrations in your project

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

You might also like