Dapper获得“指定的演员表无效”。用于ReturnValue参数值 [英] Dapper getting "Specified cast is not valid." for ReturnValue parameter value

查看:83
本文介绍了Dapper获得“指定的演员表无效”。用于ReturnValue参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用SCOPE_IDENTITY通过DynamicParameter的ReturnValue选项将长主键返回给c#。

I am trying to use SCOPE_IDENTITY to return a long primary key back to c# using the ReturnValue option for DynamicParameter.

以下是Dapper网站上的示例代码:

Here is sample code from the Dapper website:

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

Instead of returning int, I would prefer to do the following as my primary key field should be 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");

在我的proc中,我使用的是 RETURN SCOPE_IDENTITY()。

In my proc, I am using "RETURN SCOPE_IDENTITY()".

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

However doing this seems to result in a "Specified cast is not valid." exception.

推荐答案

存储过程的返回值始终隐式为整数,即 int 。因此,您只能将其视为整数。如果您尝试以 long 的形式取消装箱,它将失败。

The return value from a stored procedure is always implicitly an integer, i.e. int. As such, you can only treat it as an integer. If you try to unbox it as a long, it will fail.

选项:


  • 如果该值合适,则在.NET端将其视为 int

  • 否则,使用类型为 bigint out 参数,并将其视为 long

  • 或使用 select Query< long>(...)。Single()

  • if the value will fit, just treat it as int in the .NET side
  • otherwise use an out parameter of type bigint, and treat it as long on the .NET side
  • or use select and Query<long>(...).Single()

这篇关于Dapper获得“指定的演员表无效”。用于ReturnValue参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆