【问题标题】:AutoMapper map a collection Property value from its Parent propertyAutoMapper 从其 Parent 属性映射一个集合属性值
【发布时间】:2019-08-02 10:42:09
【问题描述】:

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

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

ReceiptProduct.cs

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; }
    }
  • ReceiptProducts.ReceiptId

  • ReceiptProducts.PurchaseOrderId

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

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

错误: AutoMapper.AutoMapperConfigurationException: Custom configuration for members is only supported for top-level individual members on a type.

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

【问题讨论】:

    标签: c# asp.net-core mapping automapper asp.net-core-2.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 ));
    

    【讨论】:

    • 有没有其他方法可以在不触及我的业务实体的情况下实现映射。
    • 不要使用映射然后只是一个新属性到您的收据实体 [NotMapped] public string ReceiptId { get { return ReceiptProducts!=null? ReceiptProducts.First().ReceiptId: string.Empty(); } }
    • 当我尝试使用映射时出现此错误 => 无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
    • .ForMember(dest => x=>x.ReceiptId,opts.MapFrom(src => src.Receipt.Id.ToString())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2015-01-11
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多