I have a Project
object, which consists of many nested objects.
To save this object to the DB:
- I change just one property within my Project (as a test), and pass it to my DAL.
- I load the existing Project from the DB with EF.
- I map the changed Project to the existing Project.
var existingProject =
db.Project.Single(p => p.ID == changedProject.ID).Include(p => p.Something);
existingProject = Mapper.Map(changedProject, existingProject);
db.SaveChanges();
This fails due to null foreign keys, which is no surprise because when I drill into the change tracker, I can see it's very confused:
var added = db.ChangeTracker.Entries().Where(e => e.State == EntityState.Added);
After the mapping takes place, a huge number of objects within the Project are marked as Added (even though nothing has been added or deleted from the project, I've only changed one property).
Is this because AutoMapper creates new instances of nested objects, and EF can't associate these with the existing objects from the DB?
I've seen this approach suggested in numerous places, is there a way for AutoMapper to work with the ChangeTracker so it understands the above - or is it better to just map everything manually? (a lot of work, in my case)