【问题标题】:Automapper: Handling Nullable Properties for Object To Object MappingAutomapper:处理对象到对象映射的可空属性
【发布时间】:2017-09-26 12:32:49
【问题描述】:

我正在使用 Automapper 6.0.2。我有一个带有以下代码的控制台应用程序。我试图通过放置对象到对象映射关系的条件来实现排序或部分更新功能。所以我正在使用:

.ForAllMembers(opt => opt.Condition(
   (source, destination, sourceMember, destMember) => sourceMember != null))

然而,Automapper 似乎在映射Mapper.Map(newViewModel, newModel) 期间将可空对象属性重新创建为具有默认值的不可空形式。我希望在下面的代码中newModel 保持不变。

预期对象

但我明白了

我该如何解决这个问题?如果我检查默认的 DateTime 和 int 值,我将被限制为 int 属性使用高于 0 的值。 我需要检查 null 而不是默认值

public class Program
{
    public static void Main(string[] args)
    {
        Mapper.Initialize(config =>
        {
            config.CreateMap<ViewModel,Model>().ForAllMembers(opt => opt.Condition(
               (source, destination, sourceMember, destMember) => sourceMember != null));
        });


        var newModel = new Model
        {
            Name = "My Name",
            Age = 18,
            DateOfBirth = new DateTime(2000, 1, 1)
        };

        var newViewModel = new ViewModel();

        //Nulls should be ignored while mapping
        Mapper.Map(newViewModel, newModel);
    }
}

public class Model
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime DateOfBirth { get; set; }
}
public class ViewModel
{
    public string Name { get; set; }
    public int? Age { get; set; }

    public DateTime? DateOfBirth { get; set; }
}

【问题讨论】:

    标签: c# mapping automapper nullable automapper-5


    【解决方案1】:

    只需按照以下方式更正您的映射

     config.CreateMap<Model, ViewModel>().ForAllMembers(opt => opt.Condition(
                   (source, destination, sourceMember, destMember) => sourceMember != null));
    

    你的映射器首先使用源然后目标

    Mapper.Map(newModel, newViewModel);
    

    【讨论】:

    • 不,这不是我想做的。我正在从可以为空的视图模型映射到模型以更新模型值。所以为了得到partial updates。我需要忽略 viewmodel 对象中的空值。你刚刚扭转了局面
    猜你喜欢
    • 2018-06-18
    • 2017-04-07
    • 1970-01-01
    • 2019-06-23
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多