I have a Project object, which consists of many nested objects.
To save this object to the DB:
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)
Destination collections are cleared first. You need AutoMapper.Collection if you want to map to existing EF collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With