2013-06-06 31 views
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版本

回答

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适用于全局类型转换。你可以阅读他的一些回复herehere

我会去的第一个你的选择:

CreateMap<Person, PersonView>() 
     .ForMember(personView => personView.Name, ex => ex.MapFrom(
      person => person.FirstName + " " + person.LastName)); 

而且很显然,价值格式化是一个mistake

+1

谢谢,这是工作,但显而易见的问题是为什么使用解析器而不是格式化程序? –

+0

我已经更新了我的答案。 – LeftyX

+0

再次感谢。我应该使用更新的书作为我的学习显然;) –