2013-06-06 52 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

再次感謝。我應該使用更新的書作爲我的學習顯然;) –