如果在AutoMapper 6中源值为null时如何保留目标值?

时间:2017-08-01 15:45:53

标签: c# automapper

首先,英语不是我的母语,所以请原谅。

来源模型:

public class Task
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

目的地模型:

public class Task2
{
    public int Id { get; set;}

    public string Title { get; set; }

    public string UserName { get; set; }
}

映射:

CreateMap<Task, Task2>()
    .ForMember(dest => dest.UserName, opt => opt.MapFrom(s => s.FirstName + " " + s.LastName))
    .ForAllMembers(opt => opt.Condition((src, dest, srcMember) => srcMember != null));

现在,问题是:

Task t = new Task(){
    Id = 0,
    Title = "blablabla",
    FirstName = null,
    LastName = null
}
Task2 t2 = new Task2(){
    Id = 0,
    Title = "blablabla",
    UserName = "Foo Bar"
}
Task2 tt = Mapper.Map<Task, Task2>(t, t2);

映射后,tt.UserName将为空。 我想保留Task2.UserName的值,但似乎不起作用。我该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以将条件放入成员配置表达式:

   .ForMember(dest => dest.UserName, opt => {
       opt.Condition(s => s.FirstName != null && s.LastName != null); // condition here
       opt.MapFrom(s => s.FirstName + " " + s.LastName);
   }); // remove all members condition

请注意,您可能不仅要检查null,还要检查空值以及使用String.IsNullOrEmptyString.IsNullOrWhitespace

输出:

{
  "Id": 0,
  "Title": "blablabla",
  "UserName": "Foo Bar"
}

答案 1 :(得分:0)

如果您的FirstNameLastNamenull,则srcMember将为空格 - " "。结果,您的条件匹配。

如果两个部分均为null,您需要更改预测以返回null,或者您需要更改条件以匹配空格。