如何使用Automapper将类映射到子类?

时间:2016-04-01 12:07:30

标签: c# automapper

如果我有课:

public class MainClass
{
   public string StringA {get; set;}
   public string StringB {get; set;}
   public string StringC {get; set;}
   public string Candy {get; set; }
}

现在我想把它映射到另一个类

public class NewClass
{
   public string StringA {get; set;}
   public string StringB {get; set;}
   public string StringC {get; set;}
   public CandyObj Candy {get; set; }
}

和CandyObj简单地说:

public class CandyObj 
{
   public string CandyID {get; set;}
   public string CandyName {get; set;}
}

如何在NewClass中处理CandyObj的映射?

我试过这条路:

    var config = new MapperConfiguration(c =>
    {
        c.CreateMap<MainClass, NewClass>()
            .ForMember(x => x.Candy.CandyID, m => m.MapFrom(a => a.Candy))
            .ForMember(x => x.Candy.CandyName, m => m.MapFrom(a => a.Candy));
    });

但我得到“Expression'x =&gt; x.Candy.CandyID'必须解析为顶级成员而不是任何子对象的属性。”

我还是AutoMapper的新手,所以任何指导都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

我发现我可以做到这一点:

        c.CreateMap<MainClass, NewClass>()
            .ForMember(x => x.Candy,
                       opts => opts.MapFrom(
                           src => new CandyObj
                           {
                               CandyID = src.Candy,
                               CandyName = src.Candy
                           }
                       ));