【问题标题】:Automapper only mapping certain propertiesAutomapper 仅映射某些属性
【发布时间】:2012-04-07 19:52:04
【问题描述】:

使用自动映射器我将我的 ViewModel 映射到我的业务对象,但是我想映射到现有的对象实例并且只映射我的视图模型上的属性。例如

ProductModel 有 id,name,code ProductBusiness 已添加 id、name、code、date

Function Add(ByVal model As ProducModel) As ActionResult
    dim _ProductBusiness = (Load ProductBusiness from db)

    dim newProductBusiness = AutoMapper.Mapper.Map(Of Business.User)(model)
End Function

我想以某种方式传入现有的业务对象实例,并且只映射两个对象上的 3 个属性,添加的日期应该与数据库中的相同。

谢谢

【问题讨论】:

    标签: .net vb.net automapper


    【解决方案1】:

    当您创建映射时,您可以忽略属性。

    不知道您是否正在寻找更复杂的东西。

    在c#中

    Mapper.CreateMap<ProductModel, ProductBusiness>()
    .ForMember(target => target.dateadded, opt => opt.Ignore());
    

    如果您不想要更通用的东西,这是可能的,但欢迎提供更多详细信息。

    【讨论】:

      【解决方案2】:

      你可以这样做:

          Public Sub MapIt(input As ProductModel, output As ProductBusiness)
              AutoMapper.Mapper.CreateMap(Of ProductModel, ProductBusiness)()
              AutoMapper.Mapper.Map(input, output)
          End Sub
      

      但请记住,您无需每次都致电CreateMapAutoMapper 将忽略 dateadded。 (还没有测试过,但我相信它会这样做)。

      或者你也可以这样做:

          Public Sub MapIt(input As c1, output As c2)
              AutoMapper.Mapper.DynamicMap(input, output)
          End Sub
      

      第二个代码与第一个代码相同DynamicMap 会为你拨打CreateMap

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多