Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make AutoMapper create an instance of class

I have the following source type:

public class Source
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

I have the following destination types:

public class Destination
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Address HomeAddress { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }
}

I created a mapping:

Mapper.CreateMap<Source, Destination>();

How do I configure my mapping so it will create an instance of Address and map the Address.PostalCode property using the Source property ZipCode?

like image 406
Dismissile Avatar asked Sep 28 '11 19:09

Dismissile


1 Answers

With AfterMap, you can specify how to map entities further after AutoMapper has done it's mapping.

Mapper.CreateMap<Source, Destination>()
                .AfterMap((src, dest) =>
                              {
                                  dest.HomeAddress = new Address {PostalCode = src.ZipCode};
                              }
            );
like image 116
scottm Avatar answered Nov 02 '22 23:11

scottm