System InvalidOperationException ("Invalid attempt to call NextResult when reader is closed.") in Microsoft.Data.Sqlite
See original GitHub issueWhen using EF core 3.0 and calling some of the DbContext methods there is a System InvalidOperation exception thrown. If I change the exception settings in VS to stop on this type of exception the description is “Invalid attempt to call NextResult when reader is closed.” For the application i am working on the exception is thrown many times in a tight loop which slows down VS considerably. When running my application outside VS it works as expected so the exception must be handled inside EF core somewhere.
This could be related to issue https://github.com/aspnet/EntityFrameworkCore/issues/17614#issuecomment-540163786 which is where I got the code to reproduce the issue.
The methods causing the exception are: context.Collection.ToList(); context.SaveChanges(); dbContext.MyObject.Find(ID); <- not able to repo this one in a simple project but is happening in the codebase I am working on.
To Reproduce
The attached simple console app reproduces the issue.
using System.ComponentModel.DataAnnotations;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace EFCore_Test
{
class Program
{
static void Main(string[] args)
{
using (var context = new MyDbContext())
{
context.Database.EnsureCreated();
var result = context.Collection.ToList(); // Throws exception.
context.Collection.Add(new MyObject());
context.SaveChanges(); // Throws exception.
result = context.Collection.ToList(); // Throws exception.
}
}
}
class MyDbContext : DbContext
{
public DbSet<MyObject> Collection { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connection = new SqliteConnection("Data Source=dbFile.Db");
connection.Open();
optionsBuilder.UseSqlite(connection);
}
}
class MyObject
{
public int Id { get; set; }
}
}
Additional context
Microsoft.Data.Sqlite version: 3.0.0 Target framework: NET Core 3.0 Operating system: Win 10 1903 EF Core 3.0.0 Visual Studio version 16.3.2
Issue Analytics
- State:
- Created 4 years ago
- Comments:12 (7 by maintainers)
Looked into this as part of #18509, and reproduced the issue.
When Dispose or Closed is called on the same SqliteDataReader more than once, the dispose logic is repeated. Part of that logic is to execute NextResult, which throws an exception is the reader has already been closed/disposed. That exception is caught and ignored in Dispose, but it does cause a needless perf slowdown and disrupts the debugging experience.
Submitted #18572 to exit Dispose early if the reader has already been closed/disposed.
PS not sure why the issue disappeared for users above, but it’s likely to be related to VS exception setting changes across versions. Confirmed that with regular EF Core code (e.g.
ctx.Blogs.ToList()
) an exception is generated internally before #18572.