Dapper.Contrib icon indicating copy to clipboard operation
Dapper.Contrib copied to clipboard

MySQL Insert does not return inserted ID if you do not open the connection first

Open oferns opened this issue 7 years ago • 1 comments

The MySql Adapter in https://github.com/StackExchange/Dapper/blob/master/Dapper.Contrib/SqlMapperExtensions.Async.cs does not check for an open connection. Consequently, if a closed connection is used, the following two commands (lines 403 & 404) are issued on separate connections. This means that the "SELECT LAST_INSERT_ID()" command will return 0.

await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout).ConfigureAwait(false);
var r = await connection.QueryAsync<dynamic>("SELECT LAST_INSERT_ID() id", transaction: transaction, commandTimeout: commandTimeout).ConfigureAwait(false);

One could fix the issue by either checking the connection is open and opening it if it isnt. Or maybe use QueryAsync and concatenate the insert query and the select query into one call.

oferns avatar Feb 19 '18 00:02 oferns

I feel calling openAsync before these commands would still not work, as that connection could get used by another call before your thread went to use it. DapperLib/Dapper#748 provided a potential solution that I put together to work around DapperLib/Dapper.Contrib#63. Combining into one query may do so, but some standard security options limit you to one query per command.

mitchcapper avatar May 28 '18 03:05 mitchcapper