I have spent too long today trying to track down an intermittent “SQLite Error 5: ‘database is locked’” error in .Net Core Entity Framework.
I have read plenty of documentation and even tried swapping to use SQL Server, as opposed to SQLite, but this just resulted in the error ‘There is already an open DataReader associated with this Connection which must be closed first.’.
So everything pointed to it being a mistake I had made.
And it was, it turns out the issue was I had the dbContext.SaveChanges() call inside a foreach loop
It was
using (var dbContext = scope.ServiceProvider.GetRequiredService()) {
var itemsToQueue = dbContext.CopyOperations.Where(o => o.RequestedStartTime < DateTime.UtcNow && o.Status == OperationStatus.Queued);
foreach (var item in itemsToQueue) {
item.Status = OperationStatus.StartRequested;
item.StartTime = DateTime.UtcNow;
dbContext.SaveChanges();
}
}
And it should have been
using (var dbContext = scope.ServiceProvider.GetRequiredService()) {
var itemsToQueue = dbContext.CopyOperations.Where(o => o.RequestedStartTime < DateTime.UtcNow && o.Status == OperationStatus.Queued);
foreach (var item in itemsToQueue) {
item.Status = OperationStatus.StartRequested;
item.StartTime = DateTime.UtcNow;
}
dbContext.SaveChanges();
}
Once this change was made my error disappeared.