问题
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