- Persist an entity is the process of inserting a new row, updating an existing row or deleting an existing row, in the database.
Connected Scenario
- It retrieves an entity from the database and persist it using the same context.
- Context object doesn’t destroy between entity retrieval and persistence.
Disconnected Scenario
- It retrieves an entity from the database and persist it using a different context.
- it is complex because new context doesn’t know anything about modified entity.
CRUD Operation in Connected Scenario
- In connected scenario, context automatically detects changes which happened in the entity, provided
AutoDetectChangesEnabled
is true by default.
var studentList = db.Students.ToList();
// Perform create operation
db.Students.Add(new Student { StudentName = "New Student" });
// Perform Update operation
var studentToUpdate = studentList
.FirstOrDefault(s => s.StudentName == "student1");
studentToUpdate.StudentName = "Edited student1";
// Perform delete operation
db.Students.Remove(studentList.First());
// Execute Insert, Update & Delete queries in the database
db.SaveChanges();
- If
AutoDetectChangesEnabled
is set to false, then context cannot detect changes made to existing entities so do not execute update query.
- You need to call
context.ChangeTracker.DetectChanges()
before SaveChanges()
in order to detect edited entities and mark their status as Modified.
- Context detects adding and deleting entity, when performed only on DbSet.
- Remember that if you perform add and delete entity on separate collection or list, then it won’t detect these changes.
- The following code will NOT insert or delete student. It will only update student:
var studentList = db.Students.ToList();
// Add student in list
studentList.Add(new Student { StudentName = "New Student" });
// Perform update operation
var studentToUpdate = studentList.
Where(s => s.StudentName == "Student1").FirstOrDefault();
studentToUpdate.StudentName = "Edited student1";
// Delete student from list
studentList.Remove(studentList.First());
// SaveChanges will only do update operation not add and delete.
db.SaveChanges();
Change Tracking
- During an entity’s lifetime, each entity has an entity state based on the operation performed on it via the context (DbContext).
- The entity state is an enum of type System.Data.EntityState that declares the following values:
- Added
- Deleted
- Modified
- Unchanged
- Detached
- The Context not only holds the reference to all the objects retrieved from the database but also it holds the entity states and maintains modifications made to the properties of the entity. This feature is known as Change Tracking.