C# 使用 Automapper 进行深层映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15554788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:09:38  来源:igfitidea点击:

Deep level mapping using Automapper

c#automapper

提问by SexyMF

I am trying to map objects with multi-level members: these are the classes:

我正在尝试使用多级成员映射对象:这些是类:

 public class Father
    {
        public int Id { get; set; }
        public Son Son { get; set; }
    }

    public class FatherModel
    {
        public int Id { get; set; }
        public int SonId { get; set; }
    }

    public class Son
    {
        public  int Id { get; set; }
    }

This is how I try automap it:

这就是我尝试自动映射它的方式:

 AutoMapper.Mapper.CreateMap<FatherModel , Father>()
                      .ForMember(dest => dest.Son.Id, opt => opt.MapFrom(src => src.SonId));

this is the exception that I get:

这是我得到的例外:

Expression 'dest => Convert(dest.Son.Id)' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead. Parameter name: lambdaExpression

表达式 'dest => Convert(dest.Son.Id)' 必须解析为顶级成员,而不是任何子对象的属性。改为在子类型或 AfterMap 选项上使用自定义解析器。参数名称:lambdaExpression

Thanks

谢谢

采纳答案by Allrameest

This will work both for mapping to a new or to an existing object.

这适用于映射到新对象或现有对象。

Mapper.CreateMap<FatherModel, Father>()
    .ForMember(x => x.Son, opt => opt.MapFrom(model => model));
Mapper.CreateMap<FatherModel, Son>()
    .ForMember(x => x.Id, opt => opt.MapFrom(model => model.SonId));

回答by Maxim

    AutoMapper.Mapper.CreateMap<FatherModel, Father>()
                     .ForMember(x => x.Son, opt => opt.ResolveUsing(model => new Son() {Id = model.SonId}));

if it's getting more complex you can write a ValueResolver class, see example here- http://automapper.codeplex.com/wikipage?title=Custom%20Value%20Resolvers

如果它变得更复杂,您可以编写 ValueResolver 类,请参见此处的示例 - http://automapper.codeplex.com/wikipage?title=Custom%20Value%20Resolvers

回答by Teja Swaroop

Use ForPath rather than ForMember & It works like magic.

使用 ForPath 而不是 ForMember & 它像魔术一样工作。