This might be by design, but it surprised me so I am filing a bug on it. Running the following simple query results in the connection remaining open after ToList has completed:
The connection is closed after the context is disposed. Including a reference does not leave the connection open.
Full repro with model:
public class MyContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(
"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=inc-test-db; Integrated Security=True;");
}
public class Program
{
public static void Main(string[] args)
{
using (var context = new MyContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
context.AddRange(
new Parent { Children = new List<Child> { new Child(), new Child() } },
new Parent { Children = new List<Child> { new Child(), new Child() } });
context.SaveChanges();
}
DbConnection dbConnection;
using (var context = new MyContext())
{
dbConnection = context.Database.GetDbConnection();
Console.WriteLine(dbConnection.State);
context.Parents.Include(u => u.Children).ToList();
//context.Children.Include(u => u.Parent).ToList();
Console.WriteLine(dbConnection.State);
}
Console.WriteLine(dbConnection.State);
}
}
public class Parent
{
public int Id { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public Parent Parent { get; set; }
}
This might be by design, but it surprised me so I am filing a bug on it. Running the following simple query results in the connection remaining open after ToList has completed:
Output:
The connection is closed after the context is disposed. Including a reference does not leave the connection open.
Full repro with model: