Will my connections close automatically in .NET Core and EF Core or do I need to close them after executing my query?

Viewed 267

I am new to using .NET Core and EF Core.

I have one sentence inside a table of my database and I have to execute like (using ADO.NET):

using (var command = context.Database.GetDbConnection().CreateCommand())
{
    command.CommandText = "<<my sql sentence>>";
    context.Database.OpenConnection();
    using (var result = command.ExecuteReader())
    {
       ....
    }
}

I found this documentation.

Is it necessary to close the connection after I execute the query? I suppose I should do it (I think), but I don't know if it is necessary, or if it will close automatically.

2 Answers

It is enough to dispose the SqlCommand after using it and leave the rest to Entity framework or ADO.NET. SQL connections use connection pooling, it means the connection remains open and can be reused by a subsequent query.

Update:

The SQL connection lives in the DbContext, the GetDbConnection() method's documentation says, it

Gets the underlying ADO.NET DbConnection for this DbContext.

This means, there is one DB connection for the DbContext, and the connection is managed by it (including features like connection resiliency). When the DbContext is disposed, also the SQL connection is disposed.

Just to add Martin answer, EFCore use a connection pool.

You can check the real count of connections in several ways.

  1. sp_who in sql server. See here.
  2. Add logging in ef core, see here.
  3. Perfmon counter, see here.
Related