Reputation: 7359
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.
Upvotes: 3
Views: 1813
Reputation: 5519
Just to add Martin answer,
EFCore
use a connection pool.
You can check the real count of connections in several ways.
Upvotes: 0
Reputation: 9490
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 thisDbContext
.
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.
Upvotes: 3