如何阻止ValueInjecter映射空值?

我正在使用ValueInjecter来映射两个相同的对象。 我遇到的问题是ValueInjector从我的源上复制了我的目标的空值。 所以我将大量数据丢失为null值。

这是我的对象的一个​​例子,有时只填写了一半,导致其空值覆盖目标对象。

public class MyObject() { public int ID { get; set; } public string Name { get; set; } public virtual ICollection OtherObjects { get; set; } } to.InjectFrom(from); 

在这种情况下,您需要创建自定义的ConventionInjection。 参见示例#2: http : //valueinjecter.codeplex.com/wikipage?title = stepme20by%20step%20explanation&referringTitle = Home

因此,您需要覆盖Match方法:

 protected override bool Match(ConventionInfo c){ //Use ConventionInfo parameter to access the source property value //For instance, return true if the property value is not null. } 

对于那些使用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(source); 

你想要这样的东西。

 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);