I'm using a type converter to convert values from a Sql Server int column to instances of a custom C# type.
In the type converter's "ConvertFrom()", I have
if (value.GetType() == typeof(int))
return SomeClass.Parse((int) value);
else if (value.GetType() == typeof(DBNull))
return null;
else
...
In the "ConvertTo()", I have
if (value == null)
return DBNull.Value;
The section that is causing the exception is in an entity's get accessor that returns the custom type.
if(valueToReturn == null)
{
valueToReturn = TypeDefaultValue.GetDefaultValue(typeof(SomeClass));
}
return (SomeClass)valueToReturn;
However, GetDefaultValue() is returning "new object()" because "defaultValueType.UnderlyingSystemType.FullName" isn't any of the cases listed. The resulting "(SomeClass)valueToReturn" downcast fails.
In response to this exception, I initially changed my type converter to return a "default" value of my custom type when ConvertFrom() gets a DBNull.Value (like "0" with Int32). Since my type is a reference type though, null is more natural, and I'd like to use that.
Returning null instead of "new object()" in "GetDefaultValue" would fix this particular issue. However, I don't know what side effects that would have. Also, there would be the usual concerns with backwards compatibility.
Is the only solution to go back to a "default" value to represent database nulls? Thanks!