How to resolve: The transaction operation cannot be performed Exception

entity-framework entity-framework-core


I am getting this error, and I have not been able to resolve:

System.Data.SqlClient.SqlException: 'The transaction operation cannot be performed because there are pending requests working on this transaction.'

What is going on is that a usual data operation is taking place as part of a Controller Action.

At the same time, there is a Filter that is running that logs the action to a database.

return this._orderEntryContext.SaveChanges() > 0;

This is where the error occurs.

So it seems to me that there is two SaveChanges going on at the same time, and so the transaction gets fouled up.

Not sure how to resolve. They are both using the same context that is gotten through DI. A workaround was to create a second context manually, but I would rather stick to the DI pattern. But I don't know how to create a second Db Context in DI, or even if that is a good idea.

Perhaps I should be using SaveChangesAsync() on both calls to ensure that they do not step on each other?

11/2/2018 10:09:12 AM

Popular Answer

Turns out the answer to this was to make the Context a transient service:

services.AddDbContext<OrderEntryContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);

Then, I changed all repositories to also be transient:

    services.AddTransient<AssociateRepository, AssociateRepository>();
6/21/2018 5:40:53 PM

Related Questions


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