如何使AutoMapper创建一个类的实例

Dis*_*ile 10 .net c# automapper

我有以下源类型:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我有以下目的地类型:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个映射:

Mapper.CreateMap<Source, Destination>();
Run Code Online (Sandbox Code Playgroud)

如何配置映射,以便创建Address实例并使用Source属性ZipCode映射Address.PostalCode属性?

sco*_*ttm 10

使用AfterMap,您可以指定在AutoMapper完成映射后如何进一步映射实体.

Mapper.CreateMap<Source, Destination>()
                .AfterMap((src, dest) =>
                              {
                                  dest.HomeAddress = new Address {PostalCode = src.ZipCode};
                              }
            );
Run Code Online (Sandbox Code Playgroud)