I have a WebApi controller in a Dotnet Core project running Entity Framework Core with Sqlite.
This code in an action occationally produces errors:
var t1 = _dbContext.Awesome.FirstOrDefaultAsync(a => [...]);
var t2 = _dbContext.Bazinga.FirstOrDefaultAsync(b => [...]);
var r1 = await t1;
var r2 = await t2;
The errors have been:
Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory:Error: An exception occurred in the database while iterating the results of a query. System.ObjectDisposedException: Safe handle has been closed
Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory:Error: An exception occurred in the database while iterating the results of a query. System.InvalidOperationException: ExecuteReader can only be called when the connection is open.
Both errors to me suggests somethings going on with the DbContext
, like premature disposing (albeit not of the DbContext
itself). The DbContext
is being injected in the controller constructor using the plumbing of Dotnet Core "the usual way", configuration as shown below (from my Startup.cs
ConfigureServices
method body):
services.AddDbContext<ApplicationContext>(options => options.UseSqlite(connectionString));
If I change the error producing code above to something like:
var r1 = await _dbContext.Awesome.FirstOrDefaultAsync(a => [...]);
var r2 = await _dbContext.Bazinga.FirstOrDefaultAsync(b => [...]);
... I haven't seen the errors mentioned, hence the conclusion that running multiple tasks concurrently on the same instance of my DbContext
(injected as described above) is what's causing the issue. Obviously, it's an unexpected one.
Questions:
- Have I come to the right conclusion, or is there something else going on?
- Can you pinpoint why the errors occur only occasionally?
- Do you know of any simple way to avoid the issue while still running concurrent tasks on the
DbContext
?
Unfortunately you can't do that.
From the EF Core documentation
Also from the EF 6 documentation
A
DbContext
only supports a single open data reader at any point in time. If you want to execute multiple simultaneous database queries you will need multipleDbContext
instances, one for each concurrent query.As to why the error occurs occasionally, its a race condition. Just because you start 2 tasks one after the next (without awaiting) does not guarantee that the database will be hit at the same time. Sometimes the execution times happen to line up and other times one task might finish right as the other task starts so there is no conflict.
How to avoid it - don't do it as its not supported. Await each of your DbContext calls or use multiple DbContext instances.
by query I mean any DB operation including SELECT, UPDATE, DELETE, INSERT, ALTER, STORED PROCEDURE CALL, ETC