When using DTOs, Automapper & Nhibernate reflecting changes in child collections of DTO in domain object being updated

对着背影说爱祢 提交于 2019-12-03 03:55:41
Betty

I recently did something similar but with EF as the datatier. I don't know nhibernate to know if the same approach would work.

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 http://groups.google.com/group/automapper-users/browse_thread/thread/8c7896fbc3f72514

    foreach (var child in source.ChildCollection)
    { 
        var targetChild = target.ChildCollection.SingleOrDefault(c => c.Equals(child)); // overwrite Equals or replace comparison with an Id comparison
        if (targetChild == null)
        { 
            target.ChildCollection.Add(Mapper.Map<SourceChildType, TargetChildType>(child));
        } 
        else
        { 
            Mapper.Map(child, targetChild);
        } 
    } 
    
  • 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.

Mapper.CreateMap<Customer, CustomerDto>()
    .ForMember(dest => dest.Categories, opt => opt.MapFrom(src =>src.Categories));

or

Mapper.CreateMap<IList<Category>, IList<CategoryDto>>();

something like this to tell automapper to map the list, too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!