Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16290

How to conditionally map to different properties?

I have the following classes:

public Company
{
    public Person Person {get; set;}
}

public Person
{ }

public Manager : Person
{ }

public Salesperson : Person
{ }

public CompanyDto
{
    public Manager Manager {get; set;}
    public Salesperon Salesperon {get; set;}
}

How can I change the following mapping so that Person is mapped to Manager if Person is of type Manager?

cfg.CreateMap<Company, CompanyDto>()
   .ForMember(dto => dto.Manager, option => option.MapFrom(model => model.Person))
   .ForMember(dto => dto.Salesperon, option => option.MapFrom(model => model.Person))
   .ReverseMap();

Upvotes: 1

Views: 75

Answers (1)

Parag
Parag

Reputation: 543

Add following mappings:

cfg.CreateMap<Person, Manager>().ReverseMap();
cfg.CreateMap<Person, Salesperson>().ReverseMap();

And you need to put condition while creating mappings like this:

cfg.CreateMap<Company, CompanyDto>()
  .ForMember(dto => dto.Manager, option => option.MapFrom(model => model.Person is Manager ? model.Person : null))
  .ForMember(dto => dto.Salesperon, option => option.MapFrom(model => model.Person is Salesperson ? model.Person : null));

For above mapping, ReverseMap will not work. You need to explicitely set the reverse mappings like this:

cfg.CreateMap<CompanyDto, Company>()
     .ForMember(dto => dto.Person, option => option.MapFrom(model => model.Manager != null ? (Person)model.Manager : model.Salesperon));

Hope this helps.

Upvotes: 2

Related Questions