Entity Framework - CRUD Operations


CRUD operation is a simple task in connected scenario because the context automatically tracks all the changes that happened in the entity during its lifetime, by default provided AutoDetectChangesEnabled is set true. If context.Configuration.AutoDetectChangesEnabled is set false then context cannot detect changes made to existing entities, so do not execute update query. You have to call context.ChangeTracker.DetectChanges() before SaveChanges() in order to detect the updated entities and change their status as modified.

Context detects adding and deleting entity, when the operation is performed only on DbSet. If add and delete entity is performed on a separate collection or list, then it will not detect these changes.

Example: Add,Update and Delete an entity in the connected scenario. Context automatically detect the changes and update the state of an entity.

using (var context = new EFSourceDBEntities())
{
  var empList = context.Employee.ToList<Employee>();
  //Create operation
  context.Employee.Add(new Employee() { Name = "XXX" });

  //Update operation
  Employee empUpdate = empList.Where(s => s.Name == "XXX").FirstOrDefault<Employee>();
    empUpdate.Name = "New Employee"

  //Delete operation
  context.Employee.Remove(empList.ElementAt<Employee>(0));

  //Execute queries in the database
  context.SaveChanges();
}

Example: Update Entity

using (var context = new EFSourceDBEntities())
{
  var empList = context.Employees.ToList<Employee>();

  //Add student in list
  empList.Add(new Employee() { Name = "New Employee" });

  //Update operation
  Employee empUpdate = empList.Where(s => s.Name == "XXX").FirstOrDefault<Employee>();
  empUpdate.Name = "employee 1"

  //Delete employee from list
  if (empList.Count > 0)
  empList.Remove(empList.ElementAt<Employee>(0));

  //SaveChanges will only do update operation not add and delete
  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