I have a custom data type called StudentID, which has an implicit conversion to string.
When I pass a StudentID instance to SqlCommand.Parameters.AddWithValue (as the value) and execute the command, I receive the following error:
"No mapping exists from object type StudentID to a known managed provider native type."
Specifying a type for the parameter like SqlDbType.NVarChar doesn't help. The only thing that works is to explicitly cast the StudentID value to a string, which defeats the purpose of having the implicit cast.
I guess the framework does not consider available conversions. Is there anything I can do to the StudentID class to make the command handle it without requiring an explicit cast to a primitive type?
This MSDN article talks about how primitive types are handled, but not user-defined types. The closest match would be object, which it says is passed as a Variant.
The exact point of failure is in the System.Data.SqlClient.MetaType.GetMetaTypeFromValue method, with signature private static MetaType GetMetaTypeFromValue(Type dataType, object value, bool inferLen)
. Reflection reveals that it looks for primative types, and if the TypeCode is object, it looks for Sql* data types such as SqlBoolean, so it seems to be looking for very specific kinds of primitive or Sql* types.