automapper可以处理某些属性不匹配的情况吗?

时间:2010-10-28 18:16:37

标签: c# automapper

假设我有一个目标类和一个大致相同的源类。几乎所有属性都使用automapper自动映射。

说出这些类中的30个属性,其中两个没有以任何方式直接进行核心化,而后者可以自动计算出来。

有没有办法告诉automapper手动连接两个属性?

例如:

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

由于可以自动映射的属性比例很高,我想使用automapper。但我阅读/观看过的文档和视频并未显示如何处理边缘情况。

有没有办法让这些类自动化?如果是,请提供代码示例?

由于

1 个答案:

答案 0 :(得分:5)

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