How to use AfterMap to map collection property properties

I have two objects and two DTOs. I map objects to DTO. Simplified versions of DTO look like this:

public class FooDto { // Other properties removed for clarity. public string Description { get; set; } public decimal Total { get; set; } public ICollection<BarDto> Bars { get; set; } } public class BarDto { // Other properties removed for clarity. public decimal Total { get; set; } } 

Classes Foo and Bar :

 public class Foo { public ICollection<Bar> Bars { get; set; } } public class Bar { // Unimportant properties } 

Display

I map this in the method as:

 public FooDto Map(IMapper mapper, Foo foo) { // _fooTotalService and _barTotalService injected elsewhere by DI. return mapper.Map<Foo, FooDto>(foo, opt => { opt.AfterMap((src, dest) => { dest.Total = _fooTotalService.GetTotal(src); dest.Bars.Total = ?????? // Needs to use _barTotalService.CalculateTotal(bar) }); }); } 

AutoMapper already has mappings configured for Foo to FooDto and Bar to BarDto, which work fine.

I need to update every BarDto in FooDto with the general use of the service (the reasons why it is too long to enter - just say that it should happen this way).

What syntax do I need to use in AfterMap to map each Total BarDto using the _barTotalService.CalculateTotal(bar) method, where Bar is the Bar in question?

Note that the _barTotalService.CalculateTotal method accepts an instance of Bar not BarDto .

+8
c # automapper
source share
1 answer

This should work -

  AutoMapper.Mapper.CreateMap<Foo, FooDto>() .AfterMap((src, dest) => { dest.Total = 8;//service call here for (var i = 0; i < dest.Bars.Count; i++) { dest.Bars.ElementAt(i).Total = 9;//service call with src.Bars.ElementAt(i) } }); AutoMapper.Mapper.CreateMap<Bar, BarDto>(); var t = AutoMapper.Mapper.Map<FooDto>(new Foo { Bars = new List<Bar> { new Bar { } } }); 
+13
source share

All Articles