5
AutoMapper를 사용하는 방법을 배우고 있으며 ValueFormatter에서 사용하는 데 문제가 있습니다.ValueFormatter가있는 AutoMapper
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; }
}
내가 여기서 무엇을 놓치고 : 나는 NameFormatter와 함께 사용할 수 없어요 곳
여기, 콘솔에서 간단한 예제? 저자 Formatters
에 따르면
public class ExampleProfile : Profile
{
protected override void Configure()
{
CreateMap<Person, PersonView>()
.ForMember(personView => personView.Name, person => person.ResolveUsing<PersonNameResolver>());
}
}
: 이런 식으로 뭔가해야
public class PersonNameResolver : ValueResolver<Person, string>
{
protected override string ResolveCore(Person value)
{
return (value == null ? string.Empty : value.FirstName + " " + value.LastName);
}
}
및 프로필 : AutoMapper 당신은 ValueResolver
(좀 더 많은 정보를 정기적으로 here)를 사용한다 버전 2.2.1
감사합니다. 이것은 작동하지만 분명한 이유는 resolver와 formatter가 아닌 이유 때문입니다. –
답변을 업데이트했습니다. – LeftyX
다시 한번 감사드립니다. 나는 분명히 나의 연구를 위해 더 최근의 책을 사용해야한다;) –