Automapper overwrites missing source property on list with child objects

后端 未结 1 1117
梦如初夏
梦如初夏 2021-01-14 05:04

I have a problem with Automapper. I set up a test windows form application and below is the code. Also look at the comments after each MessageBox:

public cla         


        
1条回答
  •  清酒与你
    2021-01-14 05:52

    I asked a similar question here and found another similar one here.

    I think @PatrickSteele makes a very good point: how is AutoMapper supposed to map a source list to a dest list of existing objects, when the dest list may not necessarily bear any resemblance to the source list? i.e. "But what if one list has 3 and the other list has 5?"

    If you are sure that FirstClass and SecondClass have the same number of Children, and if the FirstClass's Nth Child always corresponds to SecondClass's Nth child, you could try something like this:

    Mapper.CreateMap()
        .ForMember(m => m.Children, o => o.Ignore())
        .AfterMap((src, dest) =>
            {
                for (var i = 0; i < dest.Children.Count; i++)
                    Mapper.Map(src.Children[i], dest.Children[i]);
            });
    

    or if FirstChildProp is some kind of unique key:

    Mapper.CreateMap()
        .ForMember(m => m.Children, o => o.Ignore())
        .AfterMap((src, dest) =>
            {
                foreach (var dChild in dest.Children)
                {
                    var sChild = src.Children.Single(c => c.FirstChildProp == dChild.FirstChildProp);
                    Mapper.Map(sChild, dChild);
                }
            });
    

    0 讨论(0)
提交回复
热议问题