Entity Framework Core : “Invalid attempt to call ReadAsync when reader is closed”

I am new in Entity framework core, I am making a simple short project. In my project I use trigger. But when deleting multiple items, the trigger shows an error : "Invalid attempt to call ReadAsync when reader is closed”.

I googled a lot but was unable to find any solution in this situation. How can I solve this problem?

Below is my code :

 Triggers<Items>.Deleted += async e => {
       decimal convertedQuantity = e.Entity.MeasurementUnitSetup.ConversionRatio * e.Entity.IssuedQuantity;
       var warehouseItem = e.Context.Entry(e.Entity.Warehouse).Collection(o => o.WarehouseItems)
                      .Query()
                      .SingleOrDefault(wi => wi.WarehouseId == e.Entity.WarehouseId && wi.MeasurementUnitSetup.ItemId == e.Entity.MeasurementUnitSetup.ItemId);

    if (warehouseItem.Quantity - convertedQuantity >= 0)
          warehouseItem.Quantity -= convertedQuantity;

    await e.Context.SaveChangesAsync(); //From here error showing
   }

Thanks in advance.


I had the same issue because I was returning "void" in my function mistakenly:-

public async Void OnGet()

Then I replaced "void" with "Task"

public async Task OnGet()


When I came across this error it was because I was calling the DbContext actions outside the main thread which had closed and started to tidy / dispose of the necessary resources. To resolve this you will need to keep the main thread open by awaiting each database call on the main thread or by creating a new scope which can instantiate a new DbContext and keep it in scope until your action has finished.

using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();