Sunday, June 3, 2012

Updating collections using AutoMapper

By default AutoMapper replaces child lists with a completely new instance only containing the items in the original list.  Because of the way EF works you need to change the existing items in the list for it to track changes as updates instead of adds.  This method also means deletes can be tracked succesfully.
Basic steps were
Ensure the destination collection is loaded from db and attached to the object graph for change tracking
    .ForMember(dest => dest.Categories, opt => opt.UseDestinationValue())
Then create a custom IObjectMapper for mapping IList<> to IList<T> where T : Entity
The custom IObject mapper used some code from
Finally one last piece of logic to check all Id's in targetCollection exist in sourceCollection and delete them if they don't.
It wasn't all that much code in the end and is reusable in other actions.

My Stackoverflow Post:
Recently found a library that does just this -