开发者

Can automapper handle a case where the some of the properties do not match?

开发者 https://www.devze.com 2023-01-22 05:47 出处:网络
Suppose I have a destination class and a source class that are mostly the same.Almost all of the properties map automatically using automapper.

Suppose I have a destination class and a source class that are mostly the same. Almost all of the properties map automatically using automapper.

Say that of the 30 properties on these classes, two don't have a direct corelation in any way that automapper can automatically figureout.

Is there a way to tell automapper to connect two properties manually?

For Example:

class DTOMyObject
{
     public int Test {get; set;}
     public int Test2 {get; set;}
     public int Test3 {get; set;}
     public int Test4 {get; set;}
     public int Test5 {get; set;}
     // Continues for many many more properties.

     public int RandomOtherName {get; set;}
     public int SecondRandomName {get; set;}
}

class ViewMyObject
{
     public int Test {get; set;}
     public int Test2 {get; set;}
     public int Test3 {get; set;}
     public int Test4 {get; set;}
     public int Test5 {get; set;}
     // Continues for many many more properties.

     public int MapsToTheFirstRandomName {get; set;}
     public int ShouldMapToTheRandomNameThatIsSecond {get; set;}
}

Since there are a high percentage of properties that can automatically m开发者_如何学运维ap, I would like to use automapper. But the docs and videos I have read/watched do not show how to take care of the edge cases.

Is there a way to get these classes to automap? If so, please provide a code example?

Thanks


 Mapper.CreateMap<DTOMyObject, ViewMyObject>()
     .ForMember(dest => dest.MapsToTheFirstRandomName, opt => opt.MapFrom(src => src.RandomOtherName))
     .ForMember(dest => dest.ShouldMapToTheRandomNameThatIsSecond , opt => opt.MapFrom(src => src.SecondRandomName));
0

精彩评论

暂无评论...
验证码 换一张
取 消