我有两个名为ApprenticeshipDto
和Apprenticeship
的类,如下所示
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属性并自动将PersonFirstName
和PersonLastName
分配给Person对象的FirstName
和LastName
?
答案 0 :(得分:1)
是的,可以告诉AutoMapper使用custom value resolver类将DTO属性映射到目标对象属性。解析器将PersonFirstName
和PersonLastName
属性映射到新的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