SQL Server linq2db CreateTempTableAsync throws "unexpected existing transaction"

xwmevbvl  于 2023-04-28  发布在  其他
关注(0)|答案(1)|浏览(123)

We use linq2db to create a temporary table and populate it using the following code. The data connection linq2db needs is created using the ef core DbContext.

// _context is an EFCore DbContext
    var db = _context.CreateLinqToDbConnection(); 

    // items contain a list of entities
    using var tempTable = await db.CreateTempTableAsync("myTempTable", items, new BulkCopyOptions() { MaxBatchSize = maxBatchSize });

This was successfully tested by developer, validated on QA and non regression environments. On production, an exception is thrown : "unexpected existing transaction".

It seems to be related to the configuration of SqlBulkCopy being called internally by linq2db, but I don't understand what is happening here, since the code executed before does not create any transaction, and as stated before it works on non production environments.

Does it fail because of an existing ambient transaction taken from the injected DbContext ? How should I fix this code to avoid the exception ?

Tech : EfCore 6, .net 6, sql server

kmbjn2e3

kmbjn2e31#

So after further investigation, it happens that the code was interrupted because an AlwaysOn availability group failed over to a secondary server during the execution of a stored procedure that is using transaction.

相关问题