Home > database >  How to map to nested object with private field using AutoMapper
How to map to nested object with private field using AutoMapper

Time:11-19

I want to do mapping CreateMap<MoneyRangeSource, MoneyRangeDest>()

How to perform it using AutoMapper?

 public class MoneyRangeSource
 {
    public string Start { get; set; }
    public string End { get; set; }
 }

 public class MoneyRangeDest
 {        
    public Money Start { get; set; }
    public Money End { get; set; }
 }

 public class Money
 {
   private string value;

   public Money(string money)
   {            
      value = money;
   }
 }

CodePudding user response:

Set up a custom type converter for the string to Money conversion.
This allows to pass an argument to the constructor of the Money class

CreateMap<string, Money>().ConvertUsing(src => new Money(src));

and a regular mapping from MoneyRangeSource to MoneyRangeDest

CreateMap<MoneyRangeSource, MoneyRangeDest>()
  • Related