c# - Entity Framework 如何管理数据库连接?

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

假设,以下是我们的业务层:

public class DatabaseInteract
{
    //`NewsEntities` is our ObjectContext
    public List<News> GetAllNews()
    {
         return new NewsEntities().News.OrderByDescending(q => q.RegidtrationDate).ToList();
    }

    public News GetNewsById(int newsId)
    {
         return new NewsEntities().News.FirstOrDefault(q => q.Id== newsId);
    }

    public bool IsNewsExist(int newsId)
    {
         var news = new NewsEntities().News.FirstOrDefault(q => q.Id== newsId);
         return news != null;
     }
}

以下是 ASP.NET MVC 项目中的 Controller :

public ActionResult Index(int? id)
{
    DatabaseInteract databaseInteract = new DatabaseInteract();
    ViewBag.AllNews = databaseInteract.GetAllNews(id.Value);
    ViewBag.News = databaseInteract.GetNewsById(id.Value);
    ViewBag.IsExist = databaseInteract.IsNewsExist(id.Value);
    return View(model);
}

现在,我的问题是:
在调用每个业务层的方法期间,我们是否有一个与数据库的新连接?

编辑:

以下代码是否有助于确保我们在 DatabaseInteract 类的每个实例中只有一个与数据库的连接:

public class DatabaseInteract 
{
    readonly NewsEntities _entities = new NewsEntities();

    //`NewsEntities` is our ObjectContext
    public List<News> GetAllNews()
    {
         return _entities.News.OrderByDescending(q => q.RegidtrationDate).ToList();
    }

    public News GetNewsById(int newsId)
    {
         return _entities.News.FirstOrDefault(q => q.Id== newsId);
    }

    public bool IsNewsExist(int newsId)
    {
         var news = _entities.News.FirstOrDefault(q => q.Id== newsId);
         return news != null;
    }
}

最佳答案

Entity Framework 管理连接池,这意味着 EF 将在可能的情况下重用连接,并且仅在需要时创建新连接。每次调用是否创建新连接取决于许多因素。因此很难说任何给定的调用集是否会创建新连接。

总的来说,EF 在管理连接方面做得非常好,除非您知道这是一个问题,否则您不应该担心它。

关于c# - Entity Framework 如何管理数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12275252/

相关文章:

c# - 进入 VS2013 中的 lambda 表达式是否被破坏?

c# - 缺少可移植类库 WebResponse StatusCode

asp.net-mvc - 将 MVC 网站脱机并重新联机

c# - 创建、批准、编辑、批准网站内容模式

c# - EF Core 以编程方式更改隔离级别?

c# - 在 Entity Framework 4 中调用用户定义的函数

c# - 从c#中的函数返回类

c# - (N)Hibernate 在查询中选择常量

asp.net-mvc - Kendo:处理Ajax数据请求中的错误

asp.net - 问题发布网站