Problem Statement

Consider the following diagram, where there is one to many relationship between the Employee and Assest table. Here 1 Employee can have M Assests.

enter image description here

Lets say an Employee has 2 assests namely –

OldList NewList
Home Home
Bike Car

So there are 3 things to be done when updating this data using the Entity Framework

  1. Look for items present in the newlist and missing in the oldlist, these items are to be added. The item “Car” in this example.
  2. Look for items present in the oldlist and missing in the newlist, these items are to be removed. The item “Bike” in this example.
  3. And finally the items that are present in both the list. The item “Home” in this example, is to be untouched.

Code

The following code uses ExceptBy extension method to compare two lists and return based on the key passed to it.

public void UpdateEmployeeAssests(int employeeId, List<EmpAssets> updatedAssests)
{
    using (var context = new SampleDbEntities())
    {
        List<EmpAssets> oldAssests = context.EmpAssets.Where(x => x.EmployeeId == employeeId).ToList();

        List<EmpAssets> addedAssests = updatedAssests.ExceptBy(oldAssests, x => x.CityId).ToList();
        List<EmpAssets> deletedAssests = oldAssests.ExceptBy(updatedAssests, x => x.CityId).ToList();

        deletedAssests.ForEach( x => context.Entry(x).State = EntityState.Deleted);
        addedAssests.ForEach(x => context.Entry(x).State = EntityState.Added);

        context.SaveChanges();
    }
}

References: