Dapper在返回值参数中出现“指定的转换无效”的错误。

5

我正在尝试使用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");

我希望使用bigint作为我的主键字段,因此不想返回int,我更喜欢采用以下方法

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 - Marc Gravell
Dapper微ORM(扩展)。当我提到bigint时,我指的是我要保存到的表的主键字段。当我提到long时,那是我试图写入的.NET变量。 - user1790300
2个回答

6
存储过程的返回值始终是一个隐式的整数,即 int。因此,您只能将其视为整数。如果您尝试将它解包为 long,则会失败。
选项:
  • 如果该值适合,只需在 .NET 端将其视为 int
  • 否则,使用类型为 bigintout 参数,在 .NET 端将其视为 long
  • 或使用 selectQuery<long>(...).Single()

2

在这种情况下可能需要使用 bigint,因为 OP 正在使用 <long> - Marc Gravell
尝试了这个 RETURN CAST(SCOPE_IDENTITY() AS bigint),但仍然失败。 - user1790300

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接