如何将用户定义的类型传递给SqlParameterCollection.AddWithValue? [英] How should I pass a user-defined type to SqlParameterCollection.AddWithValue?
问题描述
我有一个名为StudentID
的自定义数据类型,该类型隐式转换为字符串.
I have a custom data type called StudentID
, which has an implicit conversion to string.
当我将StudentID
实例传递给SqlCommand.Parameters.AddWithValue
(作为值)并执行命令时,我收到以下错误:
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.
为像SqlDbType.NVarChar
这样的参数指定类型无济于事.唯一有效的方法是将StudentID
值显式转换为字符串,这违背了进行隐式强制转换的目的.
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.
我猜该框架没有考虑可用的转换.我可以对StudentID
类做些什么使命令处理它,而无需显式转换为原始类型?
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?
这篇MSDN文章讨论了如何处理原始类型,但不是用户定义的类型.最接近的匹配将是object,它说它是作为Variant传递的.
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.
确切的故障点在签名为private static MetaType GetMetaTypeFromValue(Type dataType, object value, bool inferLen)
的System.Data.SqlClient.MetaType.GetMetaTypeFromValue方法中.反射表明它正在寻找原始类型,如果TypeCode是对象,它将寻找Sql *数据类型,例如SqlBoolean,因此它似乎正在寻找非常特殊的原始类型或Sql *类型.
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.
推荐答案
据我所知,您不能传递UDT.仅允许使用基本类型或Sql *类型.
As I know you can't pass UDTs. Only primitive or Sql* types are allowed.
这篇关于如何将用户定义的类型传递给SqlParameterCollection.AddWithValue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!