Reputation: 22409
Assume, the following is our 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;
}
}
And the following is our Controller in an ASP.NET MVC project :
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);
}
Now, My question is :
Are we have a new connection to the database during invoking each Business Layer's method ?
Edit :
Is the following code good for confidence that we have only one connection to the database in each instance of 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;
}
}
Upvotes: 4
Views: 3727
Reputation: 93424
Entity Framework manages a connection pool, which means that EF will reuse connections when possible and only create new ones when it needs to. Whether or not each call creates a new connection depends on many factors. So it's hard to say whether any given set of calls will or will not create new connections.
In general, EF does an extremely good job of managing connections, and you shouldn't worry about it unless you know it to be a problem.
Upvotes: 8