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.
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
. Is there any way response
should contain at least values from 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);
}