假设,以下是我们的业务层:
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/