Laxmikant
Laxmikant

Reputation: 588

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.

enter image description here

Upvotes: 0

Views: 1228

Answers (1)

Yong Shun
Yong Shun

Reputation: 51160

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

Upvotes: 3

Related Questions