2012-09-20 17 views
3

如果源對象對於指定類爲空,是否可以配置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 
+0

您是否看到此問題?:http://stackoverflow.com/questions/3407838/automapper-create-instance-of-destination-type-if-source-null –

+0

是的,我看到了這個話題,但我認爲那 'Mapper.AllowNullDestinationValues = false;'和'Mapper.Configuration.AllowNullDestinationValues = false;'相同 – dmolokanov

+0

你能解釋一下,這個標誌的含義是什麼?我找不到有關它的官方文檔。 – dmolokanov

回答

0

看起來將與空替代,如果你設置Mapper.Configuration.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.Configuration.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; } 
    } 
1

它必須與已經映射的「a」相關。

var a = new A {Name = "aName"}; 
a.Init(b); 
a.Init(null); 

所有映射緩存,所以如果你試圖重新映射相同實例automapper將只保留原來的結果。

爲了測試它,嘗試:

 var c = new A {Name = "x"}; 
     c.Init(null); 

這裏是一個link到類似的問題。

相關問題