DapperLib / Dapper

Dapper - a simple object mapper for .Net
https://www.learndapper.com/
Other
17.56k stars 3.68k forks source link

In transaction, @@IDENTITY return other table id, is it a bug? #1632

Open youbl opened 3 years ago

youbl commented 3 years ago

My project use: Dapper 1.50.2 Dapper.Contrib 2.0.0 DapperExtensions 1.6.3

and my code like this:

var sql = "insert into tb(name) select 'aaa' from dual where not exists(select 1 from tb where name='aaa')";
using(var connection = factory.CreateConnection())
using(var trans = connection.BeginTransaction())
{
    if(connection.Execute(sql, null, trans) > 0) 
    {
        return Convert.ToInt64(connection.ExecuteScalar("SELECT @@IDENTITY", null, trans));
    }
}
return 0;

while I published the code, I found "SELECT @@IDENTITY" returns other table's autoId, not tb's autoId? Is my code wrong? how to fix it?

youbl commented 3 years ago

I tried use single sql like : insert into tb(name) select 'aaa' from dual where not exists(select 1 from tb where name='aaa'; select @@IDENTITY

but it always return id, even if insert SQL failed.

AdaskoTheBeAsT commented 3 years ago

Maybe you have scope_identity in mind... https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15

youbl commented 3 years ago

Maybe you have scope_identity in mind... https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15

thanks, but my db is MySQL5.7.25-log, not SQL Server.

AdaskoTheBeAsT commented 3 years ago

My bad I see - what about last_insert_id? https://dev.mysql.com/doc/c-api/8.0/en/getting-unique-id.html

youbl commented 3 years ago

@AdaskoTheBeAsT @@IDENTITY This variable is a synonym for the last_insert_id variable. It exists for compatibility with other database systems. See it here: https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

AdaskoTheBeAsT commented 3 years ago

Indeed you're right! Thanks :)

fretje commented 3 years ago

Might be the missing closing parenthesis in your "not exists" sql clause?

youbl commented 3 years ago

Might be the missing closing parenthesis in your "not exists" sql clause?

Thanks,this code is demo, my real code is right.