2017-10-13 87 views
2

从具有单个Nullable<bool>属性的对象进行映射时,我在Automapper中看到一些非常奇怪的行为。我现在有它成立这样的:自动映射器未从包含单个可为null的布尔字段的源进行映射

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.HasAnotherThingtrue如预期!

显然我不知道这里发生了什么,所以有人看过类似的东西,或者知道Automapper中可能导致这种情况的任何错误?

+0

无法使用提供的代码和automapper nuget包(即'dest.IsAThing'为true且非空)的最后一个(6.1.1)版本来重现此操作。 – Evk

+0

请编辑您的问题以包含[MCVE](https://stackoverflow.com/help/mcve),以便我们可以查看/测试您拥有的源代码。 – Progman

回答

1

我想通了,我在我的映射配置的其他地方有CreateMap<MyViewModel, MyEntity>().ForAllMembers(opt => opt.Ignore())