c# - DbContext 和连接池

标签 c# .net sql-server entity-framework dbcontext

在我继承的应用程序中,基本 Controller 中有这个,应用程序中的每个其他 Controller 都继承自该 Controller 。

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 的调用以及为特定页面调用的任何其他 Controller 。)

我的问题是 DbContext 何时创建到 SQL Server 的连接?是在创建上下文时立即执行,还是仅在执行查询时执行?

如果是前者,那么我将使用 2 倍于需要的 SQL Server 连接数,如果是后者,那么这可能不是什么大问题。

我不认为我可以在不久的将来重构它,当然不是没有理由的。我应该注意这种设计的哪些潜在缺陷?

Entity Framework 6.1.3

最佳答案

因为您没有尝试在上下文的构造函数中自己创建和传递连接,所以,是的,正如其他人所说,EF 将根据需要从连接池获取/释放连接,而不是在构造连接池时。

请注意 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.

有关详细信息,请参阅以下链接:

https://msdn.microsoft.com/en-us/data/jj729737

https://msdn.microsoft.com/en-us/data/dn456849

关于c# - DbContext 和连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30941513/

相关文章:

java - 需要 XSD 日期格式

java - com.mysql.jdbc.driver 类未找到异常

c# - 如何检查 lambda 表达式中的日期是否为空,并仅在为空时才使用今天的日期

c# - ASP.NET Core 6 MVC 中的本地化模型数据注释

c# - 在设计 View 上更改 tabcontrol 的选项卡项

c# - LINQ 性能常见问题

c# - IManExt ImportCmd 问题

.net - 调用 Web 服务时,我可以在 .net 中使用 TLS 1.2 或 1.1(如果 1.2 不可用)吗?

sql-server - 当TStoredProcedure参数的方向是pdOutput时?

sql - 在 INSTEAD OF INSERT 触发器中使用默认值