2012-05-15 44 views
4

我正在使用ValueInjecter來映射兩個相同的對象。我遇到的問題是ValueInjector將來自我的源的空值從我的目標中複製過來。所以我失去了大量的數據爲空值。如何停止ValueInjecter映射空值?

下面是我的對象的一個​​例子,它有時候只有一半填充,導致其空值覆蓋目標對象。

public class MyObject() 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<OtherObject> OtherObjects { get; set; } 
} 

to.InjectFrom(from); 

回答

1

你希望是這樣的。

public class NoNullsInjection : ConventionInjection 
{ 
    protected override bool Match(ConventionInfo c) 
    { 
     return c.SourceProp.Name == c.TargetProp.Name 
       && c.SourceProp.Value != null; 
    } 
} 

用法:

target.InjectFrom(new NoNullsInjection(), source); 
3

對於使用ValueInjecter V3 +的,ConventionInjection已被棄用。使用以下實現相同的結果:

public class NoNullsInjection : LoopInjection 
{ 
    protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp) 
    { 
     if (sp.GetValue(source) == null) return; 
     base.SetValue(source, target, sp, tp); 
    } 
} 

用法:

target.InjectFrom<NoNullsInjection>(source);