[英]Automapper convert from multiple source when one of the source is null
Similar to the question posted here , I would like to map multiple sources to one destination object. 与此处发布的问题类似,我想将多个源映射到一个目标对象。 In my case there is possibility of few source object could be null, in that case i want automapper to map rest of the properties from other sources.
在我的情况下,几乎没有源对象可以为null的可能性,在这种情况下,我希望自动映射器映射其他来源的其余属性。
public class People {
public string FirstName {get;set;}
public string LastName {get;set;}
}
public class Phone {
public string HomeNumber {get;set;}
public string Mobile {get;set;}
}
public class PeoplePhoneDto {
public string FirstName {get;set;}
public string LastName {get;set;}
public string HomeNumber {get;set;}
public string Mobile {get;set;}
}
var people = repository.GetPeople(1);
var phone = repository.GetPhone(4); // assume this returns null object
Mapper Config: 映射器配置:
Mapper.CreateMap<People, PeoplePhoneDto>()
.ForMember(d => d.FirstName, a => a.MapFrom(s => s.FirstName))
.ForMember(d => d.LastName, a => a.MapFrom(s => s.LastName));
Mapper.CreateMap<Phone, PeoplePhoneDto>()
.ForMember(d => d.HomeNumber, a => a.MapFrom(s => s.HomeNumber))
.ForMember(d => d.Mobile, a => a.MapFrom(s => s.Mobile));
Extension Method: 扩展方式:
public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source)
{
return Mapper.Map(source, destination);
}
Usage: 用法:
var response = Mapper.Map<PeoplePhoneDto>(people)
.Map(phone);
Now if the phone
is null, response
is also coming out as null
. 现在,如果
phone
为null,则response
也将显示为null
。 Is there any way response
should contain at least values from People
? response
至少应包含People
值吗?
Not sure but can we do something in the extension method: 不确定,但是我们可以在扩展方法中做些什么:
public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source)
{
if(source == null) //Do something;
return Mapper.Map(source, destination);
}
public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source)
{
if(source == null)
return destination;
return Mapper.Map(source, destination);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.