I'm trying to get a return value from an insert query using Dapper.
Here's how I try to make it work:
// 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");
}
Now to make sure my query is ok and not the source of the problem here, I implemented a similar code with my actual connector (Firebird in this case), as follows:
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();
}
What is my mistake in the Dapper code? Why is one version OK and NOT the other? I've read that Dapper executes ExecuteNonQuery() so I'm not expecting this to be the cause.
The
returning
clause acts likeselect
, in that it returns data in a results grid. As such, your query should be executed as a query. This also has the advantage that it significantly simplifies the calling code:If you need additional fields, this can be extended to use a custom return type that matches the columns coming back, or a value-tuple. For example:
or
-- edit You can access the returned values by