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);
Nicely done...thanks! Perfectly solved the issue I was running into.
ReplyDeleteFantastic! I created a more powerful version to convert zero value of nullable foreign key of my view model into my model in null value.
ReplyDeleteHere 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!
Works perfectly, thank you very much for sharing!
ReplyDeleteThank you as well.
ReplyDeleteEven though writing this comment, you still saved me some minutes :)