当从具有单个Nullable<bool>
属性的对象进行映射时,我在Automapper中看到了一些非常奇怪的行为。我目前的设置如下:
public class MyViewModel
{
public bool? IsAThing { get; set; }
}
public class MyEntity
{
public bool? IsAThing { get; set; }
public bool? HasAnotherThing { get; set; }
public string AnotherThing { get; set; }
// Lots of other fields
}
使用以下映射配置文件(具有类似的反向映射):
CreateMap<MyViewModel, MyEntity>()
.ForMember(x => x.IsAThing, opt => opt.MapFrom(y => y.IsAThing))
.ForAllOtherMembers(opt => opt.Ignore());
但是,如果我尝试执行以下操作:
var config = new AutoMapperConfig().Configure();
var mapper = config.CreateMapper();
var source = new MyViewModel { IsAThing = true };
var dest = new MyEntity();
mapper.Map(source, dest);
dest.IsAThing
为空。映射配置文件是MyViewModel
被声明为映射源的唯一位置。奇怪的是,如果我宣布班级
public class AnotherThingViewModel
{
public bool? HasAnotherThing { get; set; }
public string AnotherThing { get; set; }
}
并进行以下测试:
var source = new AnotherThingViewModel { HasAnotherThing = true };
var dest = new MyEntity();
mapper.Map(source, dest);
dest.HasAnotherThing
符合预期true
!
显然我不知道这里发生了什么,所以之前有人见过这样的事情,或者知道Automapper中可能导致这种情况的任何错误吗?
答案 0 :(得分:2)
我想通了,我的映射配置中有CreateMap<MyViewModel, MyEntity>().ForAllMembers(opt => opt.Ignore())
!