Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper complex mapping

How can I map the following:

public abstract class PersonBase
{
   public Address Address { get; set; }         
}

public class Address
{
  public string AddressHome { get; set; }
  public int PostalNumber { get; set; }
}

public class PersonEditVM : PersonBase
{ 
   public int PersonId { get; set; }
}

public PersonEntity
{
  public int PersonId { get; set; }
  public string AddressHome { get; set; }
  public int PostalNumber { get; set; }
}

I would like to map PersonEntity to PersonEditVM.

EDIT: Solved after a cup of coffee but it would be nice if it's a cleaner solution?.

Mapper.CreateMap<PersonEntity, PersonEditVM >()                
                .ForMember(d=>d.Address, s=>s.MapFrom(p=> new Address{
                    AddressHome = p.AddressHome,
                    PostalNumber = p.PostalNumber
                    }));
like image 374
Matija Grcic Avatar asked Apr 05 '12 08:04

Matija Grcic


1 Answers

Here's one way to do it, which would split your Adress (which is correctly spelled Address by the way) mapping into another CreateMap call:

Mapper.CreateMap<PersonEntity, PersonEditVM>()
    .ForMember(dest => dest.Adress, opt => opt.MapFrom(src => src));

Mapper.CreateMap<PersonEntity, Adress>()
    .ForMember(dest => dest.AdressHome, opt => opt.MapFrom(src => src.AdressHome))
    .ForMember(dest => dest.PostalNumber, opt => opt.MapFrom(src => src.PostalNumber));
like image 135
Andrew Whitaker Avatar answered Sep 28 '22 07:09

Andrew Whitaker