AutoMapper: Merging values of items in a collection from one instance to another

后端 未结 3 1354
一生所求
一生所求 2020-12-19 16:55

I am trying to figure out how to merge two complex object instances using AutoMapper. The parent object has a property which is a collection of child objects:



        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 17:21

    It's looking more and more likely that I will be unable to come up with mappings to handle this scenario; fair enough really as AutoMapper was never intended to be used to merge values in this way.

    So I have resorted to handling the collection manually within a loop. For the purposes of this answer, I am assuming that Parent.A is uniquely identifying property:

    Mapper.CreateMap()
        .ForMember(parent => parent.Children, opt => opt.Ignore());
    
    Mapper.CreateMap()
        .ForMember(child => child.C, opt => opt.Ignore());
    
    Mapper.Map(parentOne, parentTwo);
    
    foreach (var childTwo in parentTwo.Children)
    {
        var childOne = parentOne.Children.Where(child => child.A == childTwo.A).Single();
        Mapper.Map(childOne, childTwo);
    }
    

提交回复
热议问题