5
我正在学习如何使用AutoMapper,我在使用ValueFormatter时遇到了问题。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版本
谢谢,这是工作,但显而易见的问题是为什么使用解析器而不是格式化程序? –
我已经更新了我的答案。 – LeftyX
再次感谢。我应该使用更新的书作为我的学习显然;) –