gpt4 book ai didi

c# - EF Core DBContext什么时候处理Sql Connection?

转载 作者:行者123 更新时间:2023-12-04 14:48:48 25 4
gpt4 key购买 nike

使用经典 ADO.NET 时,我们通常会在执行完 SQL 命令后立即关闭 SQL 连接,因此连接会关闭并返回到池中。

类似于:

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;
}

在使用 EF Core 的 ASP.NET Core 中,我们通常使用 DI 框架将 DbContext 注入(inject)到构造函数中

      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;
}
}

我假设在幕后,DbContext 仍在使用 SqlCommandSqlConnection 连接到数据库。

我想知道 EF Core 什么时候关闭 SqlConnection?它是在执行完查询后立即关闭连接(就像我们在经典 ADO 中所做的那样)还是在释放 DbContext 时关闭连接?

所以在上面的例子中,它是在从 GetActiveOrders() 方法返回 Orders 之前还是在 OrderService 被释放时释放连接通过 DI 容器?

最佳答案

旁注:您不应该处置不属于您的东西,DI 注入(inject) DbContext(以及任何注入(inject)的对象)就是这种情况。

但要回答你的具体问题。我找不到要链接到的文档,但尽快

  • 不要通过 DbContextOptions 提供预分配的 DbConnection 对象
  • 不要通过.Database.OpenConnection 方法手动打开连接
  • 不要通过Database.BeginTransaction 方法打开显式事务

即不要自己进行一些连接管理(在这种情况下,您负责关闭/处置),EF Core 仅在需要时打开连接并在之后立即关闭它。

当需要时意味着在 SaveChanges 期间打开一个事务,直到它被提交或回滚。或者在执行 DbReader 返回查询时,直到返回的读取器被消耗或取消。换句话说,您将如何使用经典的 ADO.NET 完成它。是的,它在幕后使用 ADO.NET(至少对于关系数据库)。

这里有一些附加信息 Do I need to close the DbConnection manually when using ambient transactions with EF Core 2.1?Using EF Core to invoke stored procedure and closing connection .还有 Connection ResiliencyHow queries work文档主题。

关于c# - EF Core DBContext什么时候处理Sql Connection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69454466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com