我正在学习如何使用AutoMapper,我在使用ValueFormatter时遇到了问题。
这是Console中的一个简单示例,我无法将其与NameFormatter一起使用:
class Program
{
static void Main(string[] args)
{
Mapper.Initialize(x => x.AddProfile<ExampleProfile>());
var person = new Person {FirstName = "John", LastName = "Smith"};
PersonView oV = Mapper.Map<Person, PersonView>(person);
Console.WriteLine(oV.Name);
Console.ReadLine();
}
}
public class ExampleProfile : Profile
{
protected override void Configure()
{
//works:
//CreateMap<Person, PersonView>()
// .ForMember(personView => personView.Name, ex => ex.MapFrom(
// person => person.FirstName + " " + person.LastName));
//doesn't work:
CreateMap<Person, PersonView>()
.ForMember(personView => personView.Name,
person => person.AddFormatter<NameFormatter>());
}
}
public class NameFormatter : ValueFormatter<Person>
{
protected override string FormatValueCore(Person value)
{
return value.FirstName + " " + value.LastName;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonView
{
public string Name { get; set; }
}
我在这里缺少什么? AutoMapper是2.2.1版本
答案 0 :(得分:4)
您应该使用ValueResolver
(更多信息here):
public class PersonNameResolver : ValueResolver<Person, string>
{
protected override string ResolveCore(Person value)
{
return (value == null ? string.Empty : value.FirstName + " " + value.LastName);
}
}
,您的个人资料应该是这样的:
public class ExampleProfile : Profile
{
protected override void Configure()
{
CreateMap<Person, PersonView>()
.ForMember(personView => personView.Name, person => person.ResolveUsing<PersonNameResolver>());
}
}
根据作者Formatters
进行全局类型转换。您可以阅读他的部分回复here和here。
我会选择第一个选项:
CreateMap<Person, PersonView>()
.ForMember(personView => personView.Name, ex => ex.MapFrom(
person => person.FirstName + " " + person.LastName));
显然,值格式化程序是mistake。