C#无法从Dapper查询中获得返回值

问题描述 投票:1回答:1

我正在尝试使用Dapper从插入查询中获取返回值。

这是我尝试使其工作的方式:

// the query with a "returning" statement
// note : I have a trigger that sets the Id to a new value using the generator IF Id is null...
string SQL = "UPDATE OR INSERT INTO \"MyTable\" (\"Id\", \"Name\") " + "VALUES (@Id, @Name) RETURNING \"Id\"";
using (var conn = new FbConnection(MyConnectionString)) {
    var parameters = new DynamicParameters();
    parameters.Add("Id", null, System.Data.DbType.Int32);
    parameters.Add("Name", "newName", System.Data.DbType.String);
    // --- also add the returned parameters
    parameters.Add("retval", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
    // execute the query with Dapper....
    conn.Execute(SQL, parameters);
    // expecting the new ID here but it is ALWAYS null....!!!
    var newId = parameters.Get<object>("retval"); 
}

现在确保我的查询正常,而不是问题的根源,我使用实际的连接器(在这种情况下为Firebird)实现了类似的代码,如下所示:

using (var conn = new FbConnection(MyConnectionString)) {
    FbCommand cmd = new FbCommand(SQL, conn);
    cmd.Parameters.Add("Id", null);
    cmd.Parameters.Add("Name", "newName");
    FbParameter pRet = cmd.Parameters.Add("retval", FbDbType.Integer);
    pRet.Direction = ParameterDirection.ReturnValue;
    conn.Open();
    cmd.ExecuteNonQuery();
    // => the new value is NOT null here, it returns the correct id!!
    var newId = Convert.ToInt32(pRet.Value);
    conn.Close();
}

我在Dapper代码中有什么错误?为什么一个版本可以,而不是另一个版本(我已经读过Dapper执行ExecuteNonQuery(),所以我不希望这是原因...)

c# sql return-value dapper
1个回答
0
投票

您必须更改查询以返回ID。您可以在SQL查询末尾使用@@IDENTITYHere是手册。

© www.soinside.com 2019 - 2024. All rights reserved.