How should I pass a user-defined type to SqlParame

2019-08-08 04:58发布

问题:

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.

回答1:

As I know you can't pass UDTs. Only primitive or Sql* types are allowed.



回答2:

It seems you can use SqlUserDefinedTypeAttribute with your custom type. Take a look at the current implementation of GetMetaTypeFromValue.