EF6 – Tracking Changes in Mapped Objects

centity-framework

In a DB-first EF6 application, we have a data access layer which handles all the interaction with EF.

The objects pulled from the context are EF-generated C# classes, these are then mapped to equivalent POCOs in the business layer. This is a common suggested approach as it decouples the layers.

So whilst the application is running, some objects in the business layer get changed (some new ones may be added also, others deleted). When the changes need to be saved to the DB, the objects are mapped back to the business layer. The problem is when EF receives these objects, it has no idea which entities have changed and which haven't.

What's a good way to approach this? (given that hundreds or thousands of objects may or may not have changed)

I've seen other projects solve this by keeping track of changes in lists: NewObjects, UpdatedObjects, DeletedObjects. The obvious problem here is that whenever somethings changes, developers need to remember to update the appropriate list. This ends up with a lot of extra clutter, and it's very easy to make a mistake.

Best Answer

Entity Framework has its own change tracking mechanisms. Updating an EF entity could be as simple as this (if you're using AutoMapper):

var entity = context.Entities.First(e => e.Id == viewmodel.Id); // fetch the entity
Mapper.Map(viewmodel, entity); // Use automapper to update entity from viewmodel
context.SaveChanges();