简体   繁体   English

C#automapper嵌套集合

[英]C# automapper nested collections

I have a simple model like this one: 我有一个像这样的简单模型:

public class Order{
   public int Id { get; set; }
   ... ...
   public IList<OrderLine> OrderLines { get; set; }
}

public class OrderLine{
   public int Id { get; set; }
   public Order ParentOrder { get; set; }
   ... ...
}

What I do with Automapper is this: 我用Automapper做的是这样的:

    Mapper.CreateMap<Order, OrderDto>();
    Mapper.CreateMap<OrderLine, OrderLineDto>();
    Mapper.AssertConfigurationIsValid();

It throw an exception that says: "The property OrderLineDtos in OrderDto is not mapped, add custom mapping ..." As we use a custom syntax in our Domain and in our DomainDto, how I can specify that the collection OrderLineDtos in OrderDto corresponds to OrderLines in Order? 它抛出一个异常,说:“OrderDto中的OrderLineDtos属性未映射,添加自定义映射...”当我们在Domain和DomainDto中使用自定义语法时,我如何指定OrderDto中的OrderLineDtos集合对应于OrderLines有序吗?

Thank you 谢谢

It works in this way: 它以这种方式工作:

    Mapper.CreateMap<Order, OrderDto>()
        .ForMember(dest => dest.OrderLineDtos, opt => opt.MapFrom(src => src.OrderLines));
    Mapper.CreateMap<OrderLine, OrderLineDto>()
        .ForMember(dest => dest.ParentOrderDto, opt => opt.MapFrom(src => src.ParentOrder));
    Mapper.AssertConfigurationIsValid();

Nested collections work, as long as the names match up. 只要名称匹配,嵌套集合就可以工作。 In your DTOs, you have the name of your collection as "OrderLineDtos", but in the Order object, it's just "OrderLines". 在您的DTO中,您的集合名称为“OrderLineDtos”,但在Order对象中,它只是“OrderLines”。 If you remove the "Dtos" part of the OrderLineDtos and ParentOrderDto property names, it should all match up. 如果删除OrderLineDtos和ParentOrderDto属性名称的“Dtos”部分,它应该全部匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM