Search code examples
c#.net-coreentity-framework-coresqlconnection

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


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.


Solution

  • 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.