AutoMapper从其Parent属性映射集合Property值

时间:2019-03-12 02:45:06

标签: c# asp.net-core mapping automapper asp.net-core-2.0

我有两个模型,Receipt.csReceiptProduct.cs。我要实现的是从其父ReceiptProducts映射ICollection PurchaseOrderIdReceiptId之类的ICollection字段。

Receipt.cs

Receipt

ReceiptProduct.cs

public class Receipt
    {
        public Guid Id { get; set; }
        public string Reference { get; set; }
        public string PurchaseOrderId { get; set; }
        public virtual ICollection<ReceiptProduct> ReceiptProducts { get; set; }
    }
  • ReceiptProducts.ReceiptId <= Receipt.Id

  • ReceiptProducts.PurchaseOrderId <= Receipt.PurchaseOrderId

我尝试了以下代码。但是我得到了错误

public class ReceiptProduct
    {
        public Guid Id { get; set; }
        public string ReceiptId { get; set; }
        public string PurchaseOrderId { get; set; }
        public string ProductName { get; set; }
        public string ProductId { get; set; }
        public string Note { get; set; }
    }

错误: CreateMap<DataEntities.Receipt, BusinessEntities.Receipt>() .ForMember(dest => dest.ReceiptProducts.Select(x=>x.ReceiptId), automapper => automapper.MapFrom(src => src.Id));

那么如何映射该集合属性值。

1 个答案:

答案 0 :(得分:1)

尝试一下。

public class ReceiptProduct
{
    public Guid Id { get; set; }
    public string ReceiptId { get; set; }
    public string PurchaseOrderId { get; set; }
    public string ProductName { get; set; }
    public string ProductId { get; set; }
    public string Note { get; set; }

    **public Receipt Receipt { get; set; }**

}

映射

CreateMap<DataEntities.ReceiptProduct, BusinessEntities.Receipt>()
.ForMember(dest => x=>x.ReceiptId, opts => opts.MapFrom(src => src.Receipt.Id))
.ForMember(dest => x=>x.PurchaseOrderId , opts => opts.MapFrom(src => src.Receipt.PurchaseOrderId))
.ForMember(dest => x=>x.Reference , opts => opts.MapFrom(src => src.Receipt.Reference ));