AutoMapper可从多个来源转换 [英] AutoMapper convert from multiple sources
问题描述
假设我有两个模型类:
public class People {
public string FirstName {get;set;}
public string LastName {get;set;}
}
还有一门电话:
public class Phone {
public string Number {get;set;}
}
我想这样转换为PeoplePhoneD:
And I want to convert to a PeoplePhoneDto like this:
public class PeoplePhoneDto {
public string FirstName {get;set;}
public string LastName {get;set;}
public string PhoneNumber {get;set;}
}
比方说,我在控制器中拥有:
Let's say in my controller I have:
var people = repository.GetPeople(1);
var phone = repository.GetPhone(4);
// normally, without automapper I would made
return new PeoplePhoneDto(people, phone) ;
在这种情况下,我似乎找不到任何示例.这可能吗?
I cannot seem to find any example for this scenario. Is this possible ?
注意:仅针对此问题的示例是不真实的.
Note: Example is not-real, just for this question.
推荐答案
You cannot directly map many sources to single destination - you should apply maps one by one, as described in Andrew Whitaker answer. So, you have to define all mappings:
Mapper.CreateMap<People, PeoplePhoneDto>();
Mapper.CreateMap<Phone, PeoplePhoneDto>()
.ForMember(d => d.PhoneNumber, a => a.MapFrom(s => s.Number));
然后通过这些映射中的任何一个创建目标对象,并将其他映射应用于创建的对象.并且可以通过非常简单的扩展方法来简化此步骤:
Then create destination object by any of these mappings, and apply other mappings to created object. And this step can be simplified with very simple extension method:
public static TDestination Map<TSource, TDestination>(
this TDestination destination, TSource source)
{
return Mapper.Map(source, destination);
}
用法非常简单:
var dto = Mapper.Map<PeoplePhoneDto>(people)
.Map(phone);
这篇关于AutoMapper可从多个来源转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!