对嵌套对象使用自动映射器

Using automapper for nested objects

我正在使用配置文件并寻找以下方面的最佳方法,我的配置文件中的内容不起作用。

public EbayItemProfile()
        {
            CreateMap<Item, EbayItem>()
                .ForMember(dest => dest.Availability.ShipToLocationAvailability.Quantity, opt => opt.MapFrom(src => src.Quantity))
                .ForMember(dest => dest.Sku, opt => opt.MapFrom(src => src.Sku))
                .ForMember(dest => dest.Product.Title, opt => opt.MapFrom(src => src.Name));
        }

这是我尝试映射的一些示例对象设置

var items = new List<Item>()
            {
                new Item()
                {
                    Quantity = "2",
                    Sku = "Test-Sku-2",
                    Name = "Test-item-2"
                }
            };

至 ->

 var expected = new List<EbayItem>()
    {
        new EbayItem()
        {
            Availability = new Availability()
            {
                ShipToLocationAvailability = new ShipToLocationAvailability()
                {
                    Quantity = "2"
                }
            },
            Sku = "Test-Sku-2",
            Product = new Product()
            {
                Title = "Test-item-2"
            }
        }};

有人可以在这里提供帮助或建议吗? .NET 6.0、Automapper 11.0.0

您可以使用.ForPath()方法。我已经创建了一个映射配置文件,这应该适用于您的用例。

CreateMap<Item, EbayItem>()
            .ForPath(dest => dest.Availability.ShipToLocationAvailability.Quantity, opt => opt.MapFrom(src => src.Quantity))
            .ForMember(dest => dest.Sku, opt => opt.MapFrom(src => src.Sku))
            .ForPath(dest => dest.Product.Title, opt => opt.MapFrom(src => src.Name));