在ASP.Net MVC中管理数据库连接

时间:2015-06-29 21:55:19

标签: c# asp.net-mvc entity-framework

我是ASP.Net MVC的新手,我编写了许多具有此ivar的Controller类:

private ApplicationDbContext db = new ApplicationDbContext();

我还读到每个请求都会创建一个新的Controller实例。

我担心数据库连接流失。

我应该使用单个全局连接对象吗?或者是否在幕后发生连接池,我不应该担心它?

1 个答案:

答案 0 :(得分:1)

对于Entity Framework ORM工具it is not recommended to use DbContext as a singleton instance,因此,请避免将其保留在global.asax上。一个好的实践是将它与模式Unit of Work一起使用。 Read this article

In this another article您可以看到有关如何保留DbContext实例的示例优缺点。