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
再次感謝。我應該使用更新的書作爲我的學習顯然;) –