【问题标题】:Can automapper handle a case where the some of the properties do not match?automapper 可以处理某些属性不匹配的情况吗?
【发布时间】:2010-10-29 02:27:18
【问题描述】:

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

假设这些类的 30 个属性中,有两个在 automapper 可以自动计算的任何方面都没有直接关联。

有没有办法告诉 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;}
}

由于可以自动映射的属性比例很高,我想使用自动映射器。但是我阅读/观看的文档和视频并没有说明如何处理边缘情况。

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

谢谢

【问题讨论】:

    标签: c# automapper


    【解决方案1】:
     Mapper.CreateMap<DTOMyObject, ViewMyObject>()
         .ForMember(dest => dest.MapsToTheFirstRandomName, opt => opt.MapFrom(src => src.RandomOtherName))
         .ForMember(dest => dest.ShouldMapToTheRandomNameThatIsSecond , opt => opt.MapFrom(src => src.SecondRandomName));
    

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 2022-01-19
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多