簡體   English   中英

使用 Automapper 映射嵌套集合

[英]Mapping a nested collections using Automapper

我一直在嘗試使用 AutoMapper 將我的實體映射到我的視圖模型。 並面臨嵌套集合映射的問題。

來源

public class Consignment
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<ConsignmentLine> ConsignmentLines { get; set; }
    public ICollection<ConsignmentDocument> ConsignmentDocuments { get; set; }
}

public class ConsignmentLine
{
    public Guid Id { get; set; }
    public Guid ConsignmentId { get; set; }
    public ICollection<ConsignmentDocument> ConsignmentDocuments { get; set; }
}

public class ConsignmentDocument
{
    public Guid Id { get; set; }
    public Guid ConsignmentId { get; set; }
    public Guid ConsignmentLineId { get; set; }
    public string DocumentName { get; set; }
}

public class ConsignmentLineViewModel
{
    public Guid Id { get; set; }
    public Guid ConsignmentId { get; set; }
    public ICollection<ConsignmentDocumentViewModel> ConsignmentDocuments { get; set; }
}
 
public class ConsignmentDocumentViewModel
{
    public Guid Id { get; set; }
    public Guid ConsignmentId { get; set; }
    public Guid ConsignmentLineId { get; set; }
    public string DocumentName { get; set; }
}

目的地

public class ConsignmentDetailsViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<ConsignmentLineViewModel> ConsignmentLines { get; set; }
    public ICollection<ConsignmentDocumentViewModel> ConsignmentDocuments { get; set; }
}

我可以很容易地為每批貨物映射寄售文件,但是在為每批貨物映射寄售行時,我收到了“AutoMapper 異常”。 我知道正在生成異常是因為每個 consignmentLine 都有自己的 consignmentDocuments 集合。

現在我的自動映射器配置文件

CreateMap<Consignment, ConsignmentDetailsViewModel>()
            .ForMember(vm => vm.consignmentLineViewModel, opt => opt.MapFrom(model => model.ConsignmentLine.ToList()))
            .ForMember(vm => vm.consignmentDocumentViews, opt => opt.MapFrom(model => model.ConsignmentDocument.ToList()));

如何將它們全部映射到 ConsignmentViewModel 類?

解決了問題。

解決辦法是為ConsignmentLine創建一個map來獲取ConsignmentDocuments的集合。

CreateMap<Consignment, ConsignmentDetailsViewModel>()
        .ForMember(vm => vm.consignmentLineViewModel, opt => opt.MapFrom(model => model.ConsignmentLine))
        .ForMember(vm => vm.consignmentDocumentViews, opt => opt.MapFrom(model => model.ConsignmentDocument));

CreateMap<ConsignmentLine, ConsignmentLineViewModel>()
            .ForMember(vm => vm.consignmentDocumentViews, opt => opt.MapFrom(model => model.ConsignmentDocument));

如果您在 AutoMapper 事務中不考慮太復雜而簡單地采取行動,則可以執行所有事務。

例子:

 CreateMap<Consignment, ConsignmentDetailsViewModel>();
 CreateMap<ConsignmentLine, ConsignmentLineViewModel>();
 CreateMap<ConsignmentDocument, ConsignmentDocumentViewModel>();
 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM