简体   繁体   中英

AutoMapper - Map when destination has a list of objects

I am trying to use AutoMapper to map the Domain model to Dtos in ASP.NET Core Web API.

Domain class

public partial class Category
{
    public Category()
    {
        Products = new HashSet<Product>();
    }

    public int Id { get; set; }

    public int CategoryDiscount { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

Domain Product Class

public partial class Product
{
    public int Id { get; set; }
    public int CategoryId { get; set; }

    public decimal Price { get; set; }

    public virtual Category Category { get; set; } = null!;
}

DTO class

public class GetCategoryProductsDto
{
    public int Id { get; set; }

    public string CategoryName { get; set; } = string.Empty;

    public int CategoryDiscount { get; set; }

    public List<ProductDto> Products {  get; set; }                  

}

Mapper Configuration

CreateMap<Category, GetCategoryProductsDto>();

Everything works fine however I wanted to calculate the product price after deducting the Category Discount.

在此处输入图像描述

Solution 1: With .AfterMap()

To perform the Price calculation after mapping, you can use .AfterMap() .

CreateMap<Product, ProductDto>();
CreateMap<Category, GetCategoryProductsDto>()
        .AfterMap((src,dest) => 
        {
            dest.Products.ForEach(x => x.Price -= src.CategoryDiscount);
        });

Demo Solution 1 @ .NET Fidde


Solution 2: With Custom Value Resolver

As @Lucian suggested, a custom value resolver is another option to handle the Price calculation.

CreateMap<Product, ProductDto>()
                .ForMember(
                    dest => dest.Price, 
                    opt => opt.MapFrom((src, dest, member, context) => src.Price - src.Category.CategoryDiscount));

CreateMap<Category, GetCategoryProductsDto>();

Demo Solution 2 @ .NET Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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