How to map a class to a subclass with Automapper?

耗尽温柔 提交于 2021-01-29 03:54:11

问题


If I have a class:

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

Now I want to map that to another class

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

and CandyObj is simply:

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

How can I handle the mapping of the CandyObj in the NewClass?

I've tried to go this route:

    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));
    });

But I get "Expression 'x => x.Candy.CandyID' must resolve to top-level member and not any child object's properties."

I'm still new to AutoMapper so any guidance would be appreciated.


回答1:


I found out I can accomplish by doing this:

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


来源:https://stackoverflow.com/questions/36355951/how-to-map-a-class-to-a-subclass-with-automapper

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