dotnet / dotnet/efcore

DbConnection is not always disposed along with DbContext

Open
#33,855 1 comment 1 reaction 1 assignee Claimed by @AndriySvyryd View on GitHub
area-dbcontext consider-for-next-release customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

If you create an instance of DbContext but don't use it for anything, the RelationalConnection will not be disposed when the context is disposed. This becomes apparent when you pass an open connection to the context and tell EF to take ownership of the connection with `contextOwnsConnection: true`.

`program.cs`:
```C#
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace EFCoreBugRepro
{
internal class Program
{
static void Main()
{
// Create and open a connection to a Sql Server.
string connectionString = "Data Source=JBRIDENBAUGH\\SQLEXPRESS; Initial Catalog=Test; Integrated Security=SSPI; Encrypt=False;";
SqlConnection sqlConnection = new(connectionString);
sqlConnection.Open();

// Create an instance of your DbContext using the open connection and contextOwnsConnection = true.
DbContextOptionsBuilder optionsBuilder = new();
optionsBuilder.UseSqlServer(sqlConnection, contextOwnsConnection: true);
using (SomeDbContext someDbConext = new(optionsBuilder.Options))
{

}

// Observe that the connection state is still Open even though the db context has been disposed.
Console.WriteLine($"Sql Connection State: {sqlConnection.State}");
}

internal class SomeDbContext : DbContext
{
public SomeDbContext(DbContextOptions options) : base(options)
{ }
}
}
}
```

Received Output:
```
Sql Connection State: Open
```

Expected Output:
```
Sql Connection State: Closed
```

### Provider and version information

EF Core version: v8.0.5
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8.0
Operating system: Windows 11
IDE: Visual Studio 2022 17.8.5

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.