How do I stop ValueInjecter from mapping null values?

[亡魂溺海] 提交于 2019-12-05 17:40:34

You need to create a custom ConventionInjection in this case. See example #2: http://valueinjecter.codeplex.com/wikipage?title=step%20by%20step%20explanation&referringTitle=Home

So, you'll need to override the Match method:

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.
}

For those using ValueInjecter v3+, ConventionInjection has been deprecated. Use following to achieve same results:

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

Usage:

target.InjectFrom<NoNullsInjection>(source);
James McCormack

You want something like this.

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

Usage:

target.InjectFrom(new NoNullsInjection(), source);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!