Home > database >  Using automapper for nested objects
Using automapper for nested objects

Time:01-08

I am using profiles and looking for the best approach on the following, what I have in my profile is not working.

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));
        }

Here are some example object setups which I am trying to map

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

to ->

 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"
            }
        }};

Can anyone help or advise here? .NET 6.0, Automapper 11.0.0

CodePudding user response:

You can use the .ForPath() method. I have created a mapping profile and this should work in your use-case.

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));
  •  Tags:  
  • Related