2012-05-15 43 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);