【发布时间】:2012-09-12 19:56:15
【问题描述】:
如果指定类的源对象为空,是否可以配置 AutoMapper 将所有属性设置为默认值?我知道我应该使用Mapper.AllowNullDestinationValues = false; 为应用程序中的所有类做我想做的事情。
这是我用于测试的示例代码,但它不起作用
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
【问题讨论】:
-
你看到这个问题了吗?:stackoverflow.com/questions/3407838/…
-
是的,我看到了那个话题,但我认为
Mapper.AllowNullDestinationValues = false;和Mapper.Configuration.AllowNullDestinationValues = false;一样 -
你能解释一下,这个标志是什么意思吗?我找不到有关它的官方文档。
标签: c# automapper automapper-2