我有以下方法:
public static T ExecuteScalar<T>(
string query,
SqlConnection connection,
params SqlParameter[] parameters) where T : new()
{
// Create SqlCommand
SqlCommand command = CreateCommand(query, connection, parameters);
// Execute command using ExecuteScalar
object result = command.ExecuteScalar();
// Return value as expected type
if (result == null || result is DBNull) return default(T);
return (T)result;
}
我想MIN_ACTIVE_ROWVERSION
将数据库作为ulong
. 奇怪的是.. 下面的第一个方法调用会产生错误,但第二个方法调用工作正常。
方法调用 1产生错误:
ulong minActiveRowversion =
SqlUtils.ExecuteScalar<ulong>(
"SELECT CAST(MIN_ACTIVE_ROWVERSION() AS BIGINT)"
, _connectionString);
错误:
System.InvalidCastException: Specified cast is not valid.
方法调用 2工作正常:
ulong minActiveRowversion =
(ulong)SqlUtils.ExecuteScalar<long>(
"SELECT CAST(MIN_ACTIVE_ROWVERSION() AS BIGINT)"
, _connectionString);
我不明白这是怎么可能的,因为该command.ExecuteScalar()
方法的结果是这样的:
object result | 1955612
result.GetType() | {Name = "Int64" FullName = "System.Int64"}
- 有人能告诉我为什么第一种情况不可能,而第二种情况有效吗?
- 有人可以告诉我如何解决它,以便我可以使用场景 1。