Persistence in Entity Framework


The Persistence in Entity Framework is handled by DbContext Class. 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.

Persisting of data to the data store is the responsibility of the DBContext class. 
DBContext class is responsible for persisting of data to the data store/database. There are two scenarios in which data can be persisted in the database.

1. Connected Scenario
2. Disconnected Scenario


1. Connected Scenario

In connected scenario, context object is aware of the entity is being modified. Entity is added to the context when retrive the entity from the database. Context keeps track of the changes made to the entity. The context generates the correct SQL query(INSERT,UPDATE,DELETE) depending on the entity state (added,modified or deleted). Context object doesn't destroy between entity retrieval and persistence of entities.

The following example shows how Persistence works in Connected Scenario. In step1 context (db) is created using the Using statement. In step2 Employee entity is retrived from the database.Create,Add,Edit or Delete operations can be performed on the created entitiy. In step3 SaveChanges method is called to persist the data back to the database.

using (EFSourceContext db = new EFSourceContext())
{
  var emp = db.Employees;
  //Changes to the Employee
  emp.Name = "New Name"
  //Call db.SaveChanges
  db.SaveChanges()
}


2. Disconnected Scenario

In Disconnected Scenario, the new context is not aware of any changes made to the entity. This usually happens when entity is retrived from the database and then dispose the context. Any changes made to the entity must be submitted in the database using new context. 

The Persistence in disconnected scenario is as shown in the following example.

using (EFSourceContext db = new EFSourceContext())
{
   //Query for the entity and then dispose the entity
   var emp = db.Employees;
}

//Create a new context
using (EFSourceContext db = new EFSourceContext()) ( // Add modifed entity  db.AddRange(emp); //Change entity emp.Name = "New Name" //Call db.SaveChanges db.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