【问题标题】:Dapper getting "Specified cast is not valid." for ReturnValue parameter valueDapper 得到“指定的演员表无效”。对于 ReturnValue 参数值
【发布时间】:2013-06-19 16:55:17
【问题描述】:

我正在尝试使用 SCOPE_IDENTITY 使用 DynamicParameter 的 ReturnValue 选项将长主键返回给 c#。

这是来自 Dapper 网站的示例代码:

var p = new DynamicParameters();
p.Add("@a", 11);
p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

cnn.Execute("spMagicProc", p, commandType: commandType.StoredProcedure); 

int b = p.Get<int>("@b");
int c = p.Get<int>("@c");

我宁愿执行以下操作,而不是返回 int,因为我的主键字段应该是 bigint

var p = new DynamicParameters();
p.Add("@a", 11);
p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.Add("@c", dbType: DbType.Int64, direction: ParameterDirection.ReturnValue);

cnn.Execute("spMagicProc", p, commandType: commandType.StoredProcedure); 

int b = p.Get<int>("@b");
int c = p.Get<long>("@c");

在我的过程中,我使用的是“RETURN SCOPE_IDENTITY()”。

但是,这样做似乎会导致“指定的强制转换无效”。例外。

【问题讨论】:

  • 你能澄清一下:这是 dapper.rainbow 吗?另外:您说该字段是“bigint”-大概现在涉及.net方面。在这里,你的意思是BigInteger?还是您的意思是 Int64 又名 long? SQL server 的 bigint 映射到 c# 中的long
  • Dapper micro-orm(扩展)。当我提到 bigint 时,我指的是要保存到的表的主键字段。当我提到 long 时,这是我要写入的 .net 变量。

标签: c# stored-procedures dapper


【解决方案1】:

存储过程的返回值总是隐含的整数,即int。因此,您只能将其 视为 一个整数。如果您尝试将其拆箱为long,它将失败。

选项:

  • 如果该值适合,则在 .NET 端将其视为 int
  • 否则使用bigint 类型的out 参数,并将其视为.NET 端的long
  • 或使用selectQuery&lt;long&gt;(...).Single()

【讨论】:

    【解决方案2】:

    如果我没记错的话,SCOPE_IDENTITY() 返回一个小数(http://msdn.microsoft.com/en-us/library/ms190315.aspx),因此是无效的强制转换异常。

    您需要将其强制转换为 bigint(在 SQL 中)才能按您的意愿工作。

    【讨论】:

    • 在这种情况下可能是bigint,因为OP使用的是&lt;long&gt;
    • 试过这个 RETURN CAST(SCOPE_IDENTITY() AS bigint) 还是失败了。
    猜你喜欢
    • 2014-07-09
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多