When using classic ADO.NET we typically close the SQL connection as soon as we are done executing the SQL command, so the connection is closed and returned back to the pool.
Something like:
public Order[] GetActiveOrders()
{
var orders = new List<Orders>();
using (SqlConnection connection = new SqlConnection("connectionString"))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Select * FROM ORDERS WHERE Status = 'Active'";
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader())
{
//populate orders
}
}
}
// SQL connection is closed here and returned back to connection pool
return orders;
}
In ASP.NET Core using EF Core, we typically inject the DbContext into constructor using DI framework
public class OrderService:IDisposable
{
private readonly MyDBContext _dbContext;
public OrderService(MyDBContext dbContext)
{
_dbContext = dbContext;
}
public Order[] GetActiveOrders()
{
var orders = _dbContext.Orders.Where(x=>x.Status == 'Active').ToArray()
return orders;
}
#region Dispose
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_dbContext != null)
{
_dbContext.Dispose();
}
// Free any other managed objects here.
}
// Free any unmanaged objects here.
_disposed = true;
}
}
I am assuming under the hood, the DbContext is still using SqlCommand and SqlConnection to connect to the database.
I want to know when does EF Core close the SqlConnection? Does it close the connection as soon as it's done executing the query (like how we do in classic ADO) or when the DbContext is disposed?
So in the example above, will it dispose the connection before returning Orders from the GetActiveOrders() method or when the OrderService is disposed by the DI container?