Using ExecuteSqlCommand and SavesChanges within same transaction with EntityFramework Core

entity-framework-core

Question

I am chasing an issue with MySql / EF Core where I randomly have an exception thrown saying Nested transactions are not supported. This exception does not occur when my system is only used by one user. But when I run my tests in parallel or when I have multiple users, the exception occurs. I looked at all the code and their is nothing that could create nested transactions.

The only piece of codes that scares me so far is something like the following:

using (var transaction = _context.Database.BeginTransaction())
{
    // Create a few entities and add them to the EF context
    ...

    // Insert the rows: hopefully at this point, my transaction is not commited yet.
    _context.SaveChanges();

    // I then want to update a few rows with a raw sql statement without 
    // having to load the entities in memory.   
    _context.Database.ExecuteSqlCommand("UPDATE ...");

    // Now that I have inserted and inserted some data, I want to commit all these 
    // changes atomically.
    transaction.Commit();
}

Is this safe? Am I guaranteed that my SaveChanges and ExecuteSqlCommand will be executed on the same MySqlConnection? I have the feeling that when I call SaveChanges, it closes my connection and puts it back on the connection pool. Then, my ExecuteSqlCommand takes a new connection from the pool (it may be the same one or another one). So my initial connection (the one where I opened the transaction) is put back in the pool and it could be reused by another thread.

This is just a hunch and I am totally not sure if this could cause the problem.

My real question in the end is:

  • is it safe to use SaveChanges and ExecuteSqlCommand within a transaction?
1
3
10/5/2017 9:14:25 AM

Popular Answer

I upgraded from MySql.Data.EntityFrameworkCore/MySql.Data 6.10.1-beta to 6.10.3-rc and it looks like the problem is gone. Since the problem was random I can't be totally sure that the problem is indeed fixed, but so far so good.

1
10/5/2017 2:17:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow