How do I stop ValueInjecter from mapping null values?
Asked Answered
A

3

4

I am using ValueInjecter to map two identical objects. The problem I am having is that ValueInjector copies null values from my source over my target. So I am loosing lots of data to null values.

Here's an example of my object which is sometimes only half filled out which results in its null values overwriting the target object.

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

to.InjectFrom(from);
Avicenna answered 15/5, 2012 at 21:15 Comment(0)
P
1

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.
}
Pregnancy answered 15/5, 2012 at 22:31 Comment(0)
D
3

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);
Deragon answered 4/5, 2016 at 12:32 Comment(0)
P
1

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.
}
Pregnancy answered 15/5, 2012 at 22:31 Comment(0)
S
1

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);
Stendhal answered 16/5, 2014 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.