5

我正在学习如何使用 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

1 回答 1

4

您应该使用(这里ValueResolver有更多信息):

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

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

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

显然值格式化程序是一个错误

于 2013-06-06T10:07:52.023 回答