使用Automapper映射嵌套的集合

时间:2020-08-23 11:07:02

标签: c# asp.net-core entity-framework-core automapper nested-object

我一直在尝试使用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; }
}

我可以很容易地为每个托运商品映射consignmentDocuments,但是在为每个托运商品映射发货单时,我会收到“ AutoMapper Exception”。我知道正在生成异常,因为每个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类?

2 个答案:

答案 0 :(得分:0)

解决了问题。

解决方案是为ConsignmentLine创建地图以获取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));

答案 1 :(得分:0)

如果您只是简单地考虑了AutoMapper交易中的复杂性,则可以执行所有交易。

示例:

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