使用Automapper创建一个基于内置数据类型的对象

时间:2015-04-12 10:20:30

标签: c# automapper

我有两个名为ApprenticeshipDtoApprenticeship的类,如下所示

public class ApprenticeshipDto
{
    public int Id { get; set; }
    public string PersonFirstName { get; set; }
    public string PersonLastName { get; set; }
}

 public class Apprenticeship
 {
     public virtual int Id { get; set; }
     public Person Person { get; set; }      
 }

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

这就是我试图将ApprenticeshipDto映射到学徒期的方式:

Mapper.CreateMap<ApprenticeshipDto, Apprenticeship>();

Apprenticeship a = Mapper.Map<Apprenticeship>(Apprdto);

问题是所有属性都已正确映射但不是Person。 是否可以告诉Automapper创建Person属性并自动将PersonFirstNamePersonLastName分配给Person对象的FirstNameLastName

1 个答案:

答案 0 :(得分:1)

是的,可以告诉AutoMapper使用custom value resolver类将DTO属性映射到目标对象属性。解析器将PersonFirstNamePersonLastName属性映射到新的Person对象:

// create the resolver class 
// -> extract person info from DTO and return a new Person object
public class CustomResolver : ValueResolver<ApprenticeshipDto, Person>
{
    protected override Person ResolveCore(ApprenticeshipDto source)
    {
        return new Person
            {
                    FirstName = source.PersonFirstName,
                    LastName = source.PersonLastName
            };
    }
}

然后在映射之前使用AutoMapper配置中的新自定义解析器类:

Mapper.CreateMap<ApprenticeshipDto, Apprenticeship>();

var adto = new ApprenticeshipDto
{
    Id = 10,
    PersonFirstName = "John",
    PersonLastName = "Doe"
};
// configure custom mapping
Mapper.CreateMap<ApprenticeshipDto, Apprenticeship>()
    .ForMember(destination => destination.Person, opt => opt.ResolveUsing<CustomResolver>());
Apprenticeship a = Mapper.Map<Apprenticeship>(adto);
Console.WriteLine("{0} - {1} - {2}", a.Id, a.Person.FirstName, a.Person.LastName);

输出符合预期:

10 - John - Doe