Entity Framework Working with DbContext


The Entity Framework enables to query, insert, update, and delete data, using common language runtime (CLR) objects (entities). The Entity Framework maps the entities and relationships that are defined in the model to a database. The Entity Framework provides facilities to do the following:
a. Materialize data returned from the database as entity objects;
b. Track changes that were made to the objects;
c. Handle concurrency;
d. Propagate object changes back to the database;
e. And bind objects to controls.

System.Data.Entity.DbContext is the primary class that is responsible for the interaction with data as object. The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.

DbContext class is responsible for the followings:

EntitySet: DbContext class contains entity set DbSet<TEntity> for all the entities mapped to DB tables.
Querying: DbContext class converts LINQ-to-Entities Queries to SQL Query and send it to database.
Change Tracking: DbContext class keeps track of changes that occurred in the entities after it has been querying from the database.
Persisting Data: DbContext class also performs the Insert, Update and Delete operations to the database, based on the entity states.
Caching: By default first level caching is done by DbContext class. It stores the entities which have been retrieved during the life time of a context class.
Manage Relationship: DbContext class manages relationship using CSDL, MSL and SSDL in DB-First or Model-First approach or using fluent API in Code-First approach.
Object Materialization: DbContext class converts raw table data into entity objects.

Defining a DbContext derived class

The recommended way to work with context is to define a class that is derived from Dbcontext and exposes DbSet properties that represent collections of the specified entities in the context. EF Designer create the context class itself and in Code First, need to write the context class separatly.

public class EmployeeContext : DbContext
{
       public EmployeeContext() : base("EmployeeContext") { }
       public DbSet Addresses { get; set; }
       public DbSet Employees { get; set; } 
}

Queries

A query is executed when:
    1. It is enumerated by a foreach (C#) or For Each (Visual Basic) statement.
    2. It is enumerated by a collection operation such as ToArray, ToDictionary or ToList.
    3. With LINQ operators such as First or Any are specified in the outermost part of the query.
    4. Following methods are called: the Load extension method on a DbSet, DbEntityEntry.Reload, and Database.ExecuteSqlCommand.

Three types of queries can be used such as −
    1. Adding a new entity.
    2. Changing or updating the property values of an existing entity.
    3. Deleting an existing entity.

1. Adding a new entity
Adding new object with Entity Framework is as simple as constructing a new instance of the object and registering it using the Add method on DbSet. For example, following code shows how to add new employee

private static void AddEmployee()
{
      using (var context = new EmployeeContext())
         {
               var Employee = new Employee 
                   {
		             FirstName = "ABC",         
 		             LastName = "XYZ",         
		             JoiningDate = DateTime.Parse("2017-10-02")
		       };
	          context.Employees.Add(Employee);
	          context.SaveChanges();
          }
}

2. Changing or updating the property values of an existing entity
Changing the existing objects is as simple as updating the value assigned to the property(s) that needs to be changed and calling SaveChanges. In the following code, the last name of Ali has been changed from Khan to Aslam.

private static void EditEmployee(int EmpId) 
{
     using (var context = new EmployeeContext()) 
          {
	        var Employee = (from e in context.Employees where e.EmpId = EmpId select e).FirstOrDefault();
	        Employee.LastName = "ABC";
	        Employee.FirstNAme="XYZ",
	        context.SaveChanges();
           }
}

3. Deleting an Existing Entities
Use the Remove method on DbSet to delete an entity using Entity Framework. Remove method works for both existing and recently added entities. Calling Remove method on the entity that is added but not saved yet to the database will cancel the addition of the entity. The entity will be removed from the change tracker and is no longer tracked by the DbContext. Calling Remove method on an existing entity that is being change tracked will register the entity for deletion the next time SaveChanges is called.

private static void DeleteEmployee(int EmpId) 
{
       using (var context = new EmployeeContext()) 
           {
 	        var Employee = (from e in context.Employees where e.EmpId = EmpId select e).FirstOrDefault();
         	context.Employees.Remove(Employee);
	        context.SaveChanges();
            }
}

 

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More