DbContext 和连接池
DbContext and Connection pools
在我继承的应用程序中,基本控制器中有这个,应用程序中的每个其他控制器都继承自该控制器。
public BaseController()
{
db = new MyDbContext();
db.Database.Log = s => Debug.Write(s);
}
public MyDbContext()
: base("name=MyDbContext")
{
// hack to force Visual Studio to deploy the Entityframework.SqlServer package
var instance = SqlProviderServices.Instance;
}
由于应用程序的设计方式,每个请求至少创建 2 个上下文。 (这是一个 MVC 应用程序,每个页面上都会调用 HomeController 以及为特定页面调用的任何其他控制器。)
我的问题是 DbContext
何时创建到 SQL 服务器的连接?是在创建上下文时立即执行,还是仅在执行查询时执行?
如果是前者,那么我将使用 2 倍于 SQL 服务器的连接数,如果是后者,那么这可能不是什么大问题。
我不认为我可以在不久的将来重构它,当然不是没有理由的。我应该注意这种设计的哪些潜在缺陷?
Entity Framework6.1.3
仅在执行查询时打开连接。连接池由 ADO.NET 类 (SqlConnection) 管理。每个请求有多个 DbContext 实例是可以的,有时是必要的。一般来说,您不会有两倍的连接数。
Entity Framework遵循晚开早关的原则。所以,它只在需要时打开连接,IE 来实现查询,然后尽快关闭它。
如果可以,您应该针对每个请求移动到一个上下文实例。这也将请求期间发生的所有事情都保存在一个事务中。如果您使用依赖注入容器来实例化您的控制器,您可以很容易地做到这一点。
因为您没有尝试在上下文的构造函数中自己创建和传递连接,所以,是的,正如其他人所说,EF 将根据需要 get/release 来自连接池的连接,而不是在需要时建造。
请注意 EF 文档中的这句话:
Connections
By default, the context manages connections to the database. The context opens and closes connections as needed. For example, the context opens a connection to execute a query, and then closes the connection when all the result sets have been processed.
There are cases when you want to have more control over when the connection opens and closes. For example, when working with SQL Server Compact, opening and closing the same connection is expensive. You can manage this process manually by using the Connection property.
有关详细信息,请参阅以下链接:
在我继承的应用程序中,基本控制器中有这个,应用程序中的每个其他控制器都继承自该控制器。
public BaseController()
{
db = new MyDbContext();
db.Database.Log = s => Debug.Write(s);
}
public MyDbContext()
: base("name=MyDbContext")
{
// hack to force Visual Studio to deploy the Entityframework.SqlServer package
var instance = SqlProviderServices.Instance;
}
由于应用程序的设计方式,每个请求至少创建 2 个上下文。 (这是一个 MVC 应用程序,每个页面上都会调用 HomeController 以及为特定页面调用的任何其他控制器。)
我的问题是 DbContext
何时创建到 SQL 服务器的连接?是在创建上下文时立即执行,还是仅在执行查询时执行?
如果是前者,那么我将使用 2 倍于 SQL 服务器的连接数,如果是后者,那么这可能不是什么大问题。
我不认为我可以在不久的将来重构它,当然不是没有理由的。我应该注意这种设计的哪些潜在缺陷?
Entity Framework6.1.3
仅在执行查询时打开连接。连接池由 ADO.NET 类 (SqlConnection) 管理。每个请求有多个 DbContext 实例是可以的,有时是必要的。一般来说,您不会有两倍的连接数。
Entity Framework遵循晚开早关的原则。所以,它只在需要时打开连接,IE 来实现查询,然后尽快关闭它。
如果可以,您应该针对每个请求移动到一个上下文实例。这也将请求期间发生的所有事情都保存在一个事务中。如果您使用依赖注入容器来实例化您的控制器,您可以很容易地做到这一点。
因为您没有尝试在上下文的构造函数中自己创建和传递连接,所以,是的,正如其他人所说,EF 将根据需要 get/release 来自连接池的连接,而不是在需要时建造。
请注意 EF 文档中的这句话:
Connections
By default, the context manages connections to the database. The context opens and closes connections as needed. For example, the context opens a connection to execute a query, and then closes the connection when all the result sets have been processed.
There are cases when you want to have more control over when the connection opens and closes. For example, when working with SQL Server Compact, opening and closing the same connection is expensive. You can manage this process manually by using the Connection property.
有关详细信息,请参阅以下链接: