How should I pass a user-defined type to SqlParameterCollection.AddWithValue?

此生再无相见时 提交于 2019-12-11 05:05:02

问题


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.



来源:https://stackoverflow.com/questions/767072/how-should-i-pass-a-user-defined-type-to-sqlparametercollection-addwithvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!