18 Jan 2012

ValueInjecter - matching nullable to non-nullable values

Here's a little ValueInjecter plugin I wrote to handle ValueInjecter matching for properties where the name matches but one is nullable and the other is not.
        
public class NullableInjection : ConventionInjection
{
 protected override bool Match(ConventionInfo c)
 {
  return c.SourceProp.Name == c.TargetProp.Name &&
      (c.SourceProp.Type == c.TargetProp.Type 
    || c.SourceProp.Type == Nullable.GetUnderlyingType(c.TargetProp.Type)
    || (Nullable.GetUnderlyingType(c.SourceProp.Type) == c.TargetProp.Type 
      && c.SourceProp.Value != null )
    );
 }

 protected override object SetValue(ConventionInfo c)
 {
  return c.SourceProp.Value;
 }
}

So I just use it like so:
targetModel.InjectFrom<NullableInjection>(sourceModel);

4 comments:

  1. Anonymous2:13 am

    Nicely done...thanks! Perfectly solved the issue I was running into.

    ReplyDelete
  2. Fantastic! I created a more powerful version to convert zero value of nullable foreign key of my view model into my model in null value.

    Here is a preview:

    protected override bool Match(ConventionInfo c)
    {
    _convertToNull = false;

    if (c.SourceProp.Name == c.TargetProp.Name)
    {
    if (Nullable.GetUnderlyingType(c.TargetProp.Type) == typeof(short) || Nullable.GetUnderlyingType(c.TargetProp.Type) == typeof(int) || Nullable.GetUnderlyingType(c.TargetProp.Type) == typeof(long))
    {
    if (c.SourceProp.Name.Length > 2)
    {
    if (c.SourceProp.Name.EndsWith("Id"))
    {
    if (c.SourceProp.Type == c.TargetProp.Type
    || c.SourceProp.Type == Nullable.GetUnderlyingType(c.TargetProp.Type)
    || (Nullable.GetUnderlyingType(c.SourceProp.Type) == c.TargetProp.Type))
    {
    if (Convert.ToInt64(c.SourceProp.Value) == 0)
    {
    _convertToNull = true;

    if (!this.FullInjection)
    return true;
    }
    }
    }
    }
    }

    if (this.FullInjection)
    return true;
    }

    return false;
    }

    protected override object SetValue(ConventionInfo c)
    {
    if (this.FullInjection)
    {
    if (_convertToNull)
    return null;
    else
    return c.SourceProp.Value;
    }
    else
    return null;
    }

    Thank you again for your help!

    ReplyDelete
  3. Works perfectly, thank you very much for sharing!

    ReplyDelete
  4. Thank you as well.
    Even though writing this comment, you still saved me some minutes :)

    ReplyDelete

Comments are very welcome unless you're a spammer, in which case you should probably kill yourself.

If I helped you out today, you can buy me a beer below. Cheers!