假设,以下是我们的 BusinessLayer :
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 项目中的控制器:
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
Class 的每个实例中只有一个与数据库的连接:
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;
}
}