[英]Automapper: Handling Nullable Properties for Object To Object Mapping
I am using Automapper 6.0.2. 我正在使用Automapper 6.0.2。 I have a console application with the following code below. 我有一个带有以下代码的控制台应用程序。 I am trying to achieve a sort or partial update feature by placing a condition for the object to object mapping relationship. 我试图通过放置对象到对象映射关系的条件来实现排序或部分更新功能。 So I am using: 所以我正在使用:
.ForAllMembers(opt => opt.Condition(
(source, destination, sourceMember, destMember) => sourceMember != null))
However it seems Automapper recreates the nullable object properties as non nullable forms with default values during the mapping Mapper.Map(newViewModel, newModel)
. 但是,似乎Mapper.Map(newViewModel, newModel)
在映射Mapper.Map(newViewModel, newModel)
期间将空值对象属性重新创建为具有默认值的非空值形式。 I would expect that in the code below newModel
stays unchanged. 我希望在newModel
下面的代码中保持不变。
Expected Object 预期对象
But I Get 但是我明白了
How do I get around this? 我该如何解决? If I check for default DateTime and int values, I will be constrained to using values above 0 for the int property. 如果我检查默认的DateTime和int值,则必须将int属性的值设置为大于0。 I need to check for null not default values 我需要检查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; }
}
just correct your mapping as followed 只需按照以下方式更正您的映射
config.CreateMap<Model, ViewModel>().ForAllMembers(opt => opt.Condition(
(source, destination, sourceMember, destMember) => sourceMember != null));
and your mapper use source first then target 然后您的映射器先使用源,然后再定位
Mapper.Map(newModel, newViewModel);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.