如何在AutoMapper中有条件地从两个源映射到目标

时间:2017-01-30 05:56:12

标签: automapper

我有一个PITA遗留数据库模型。这是相关部分

class SalesOrder
{
  public  Recipient OrderBy {get;set;}
  public  Recipient BillTo {get;set;}
  public  List<SalesOrderLine> Lines {get;set;}
}

class SalesOrderLine
{
 public  Recipient ShipTo {get;set;}
 public  Address ShipToAddress {get;set;}
}

class Recipient
{
   public  Address DefaultAddress {get;set;}
}

Now comes the fun part.

class RecipientDTO {
 public string   Name {get;set;}
 public string   Address1 {get;set;}
 public string   Address2 {get;set;}
...
}

我的OrderDTO需要像这样

    new OrderDTO {
      OrderBy  = new RecipientDTO {
       Name = OrderBy.Name,
       Address1 = OrderBy.DefaultAddress.Addr1,
      ....
}
      BillTo = new RecipientDTO {
       Name = BillTo.Name,
       Address1 = BilLTo.DefaultAddress.Addr1,
      ....
}

     Lines = Lines.Select (l => new SalesOrderLineDTO {
                ShipTo = new RecipientDTO {
       Name = ShipTo.Name,
       Address1 = l.ShipToAddress.Addr1, //NOTE. THIS IS NOT USING DEFAULT ADDRESS
      ....
} 
    } )
    }

如何在Auto Mapper中编写映射配置,以确保投影发出所选列。如果我使用CustomResolver,则投影不会发出sql,每次访问该地址时都会进入数据库。穆乔伤心!

1 个答案:

答案 0 :(得分:0)

对于任何有兴趣的人,我都会对地址收件人进行反向引用。

之后,我能够做到这一点
                m.CreateMap<SalesOrder, OrderDTO>()
                   .ForMember(d => d.OrderBy, conf => conf.MapFrom(o => o.OrderBy.DefaultAddress))
                   .ForMember(d => d.BillTo, conf => conf.MapFrom(o => o.BillTo.DefaultAddress));
                m.CreateMap<Address, RecipientDTO>()
                    .ForMember(r => r.CustomerRecipientId, conf => conf.MapFrom(ra => ra.Recipient.CustRecipId))
                    .ForMember(r => r.Address1, conf => conf.MapFrom(ra => ra.Addr1))
                    .ForMember(r => r.Address2, conf => conf.MapFrom(ra => ra.Addr2))
....
                m.CreateMap<SalesOrderLine, OrderLineDTO>()
                    .ForMember(l => l.OrderQuantity, conf => conf.MapFrom(l => l.OrderQty ?? 0))
                    .ForMember(l => l.ShipTo, conf => conf.MapFrom(z => z.ShipToAddress));