当源之一为空时,自动映射器从多个源转换

时间:2019-03-02 23:52:00

标签: c# automapper

类似于发布的问题here,我想将多个源映射到一个目标对象。就我而言,可能很少有源对象可以为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.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));

扩展方法:

public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source)
{
    return Mapper.Map(source, destination);
}

用法:

var response = Mapper.Map<PeoplePhoneDto>(people)
                .Map(phone);

现在,如果phone为空,则response也将以null的形式出现。 response是否应该至少包含People中的值?

不确定,但是我们可以在扩展方法中做些什么:

public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source)
{
    if(source == null) //Do something;
    return Mapper.Map(source, destination);
}

1 个答案:

答案 0 :(得分:0)

public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source)
{
    if(source == null)
        return destination;

    return Mapper.Map(source, destination);
}