dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.62k stars 3.15k forks source link

Query: Connection is not closed after executing a query including a collection #6581

Closed ajcvickers closed 7 years ago

ajcvickers commented 7 years ago

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:

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);

Output:

Closed
Open
Closed

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; }
}
divega commented 7 years ago

Reopening to go through proper approval process.

Eilon commented 7 years ago

This patch is approved, please ensure it is merged into the correct branch and building as part of the patch train.