我正在学习如何使用 AutoMapper,但在使用 ValueFormatter 时遇到了问题。
这是控制台中的简单示例,我无法将它与 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 版