如果源對象對於指定類爲空,是否可以配置AutoMapper將所有屬性設置爲默認值?我知道我應該使用Mapper.AllowNullDestinationValues = false;
來做我想要的應用程序中的所有類。 這裏採樣代碼,我使用的測試,但它不工作AutoMapper:如果源對象對於指定類型爲空,則將目標對象的所有屬性設置爲默認值
public class A
{
static A()
{
Mapper.Initialize(
config =>
{
config.ForSourceType<B>().AllowNullDestinationValues = false;
config.CreateMap<B, A>()
.ForMember(member => member.Name, opt => opt.Ignore());
});
//Mapper.AllowNullDestinationValues = false;
Mapper.AssertConfigurationIsValid();
}
public void Init(B b)
{
Mapper.DynamicMap(b, this);
}
public int? Foo { get; set; }
public double? Foo1 { get; set; }
public bool Foo2 { get; set; }
public string Name { get; set; }
}
public class B
{
public string Name { get; set; }
public int? Foo { get; set; }
public double? Foo1 { get; set; }
public bool Foo2 { get; set; }
}
使用此代碼:
var b = new B() {Foo = 1, Foo1 = 3.3, Foo2 = true, Name = "123"};
var a = new A {Name = "aName"};
a.Init(b); // All ok: Name=aName, Foo=1, Foo1=3,3, Foo2=True
a.Init(null); // Should be Name=aName, Foo=null, Foo1=null, Foo2=False,
// but a has the same values as on a previous line
您是否看到此問題?:http://stackoverflow.com/questions/3407838/automapper-create-instance-of-destination-type-if-source-null –
是的,我看到了這個話題,但我認爲那 'Mapper.AllowNullDestinationValues = false;'和'Mapper.Configuration.AllowNullDestinationValues = false;'相同 – dmolokanov
你能解釋一下,這個標誌的含義是什麼?我找不到有關它的官方文檔。 – dmolokanov