Using ExecuteSqlCommand and SavesChanges within same transaction with EntityFramework Core

Deadly 提交于 2019-12-10 21:27:40

问题


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:


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.



来源:https://stackoverflow.com/questions/46576344/using-executesqlcommand-and-saveschanges-within-same-transaction-with-entityfram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!