0

After upgrading .NET core version from 2.2 to 3.0 I got error on this:

_repository.Insert(new RequestStatusHistory()
{
 RequestId = requestModel.Id ,
 RequestStatusId = newRequestStatusId 
});


public void Insert(T entity)
{         
 this._entity.Add(entity);
 _context.SaveChanges();
}

And the error is:

New transaction is not allowed because there are other threads running in the session

What should I do? `

Mahdi
  • 526
  • 2
  • 5
  • 16
  • Check this: [https://stackoverflow.com/questions/2113498/sqlexception-from-entity-framework-new-transaction-is-not-allowed-because-ther](https://stackoverflow.com/questions/2113498/sqlexception-from-entity-framework-new-transaction-is-not-allowed-because-ther) – Hadi Samadzad Dec 08 '19 at 12:57
  • I don't have any loop! – Mahdi Dec 08 '19 at 13:41
  • 1
    Add more details about the repositories `Insert` method to the question. – Hadi Samadzad Dec 08 '19 at 13:46
  • You are calling single database context in multiple methods. if you use foreach loop to insert, don't call savechanges inside foreach loop – phonemyatt Dec 09 '19 at 05:20
  • The bug was there from the start, you just didn't notice it. You're using a DbContext from multiple threads *and* using the Generic Repository **anti**pattern. How many insertions is that `SaveChanges` going to make? 1? 2? 10? You have no way of knowing. `SaveChanges` persists **all** changes since the last time it was called. It can easily perform some updates and deletions too. Contexts are meant to be short-lived too, just like connections – Panagiotis Kanavos Dec 10 '19 at 15:50
  • The solution is to *not* use the generic repository and *not* use a global context. A DbContext is essentially a UoW, by creating a global one you're breaking that functionality. Check [No Need for Repositories and Unit of Work with Entity Framework Core](https://gunnarpeipman.com/ef-core-repository-unit-of-work/) for a detailed explanation – Panagiotis Kanavos Dec 10 '19 at 15:51
  • If you *remove* `Insert` altogether, add any entities you want normally with `DbSet.Add` and only call `SaveChanges` just once, just before you dispose the context, you'll probably get rid of the problem and improve performance a lot. The error complains there are multiple active transactions. Perhaps you explicitly tried to start one, even though `SaveChanges` is atomic? Or you are still reading from a query? Without the call that called `Insert` it's impossible to say – Panagiotis Kanavos Dec 10 '19 at 15:58

0 Answers0