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

时间:2011-09-28 19:15:44

标签: c# .net 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; }
}

我有以下目的地类型:

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; }
}

我创建了一个映射:

Mapper.CreateMap<Source, Destination>();

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

1 个答案:

答案 0 :(得分:9)

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

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