Reputation: 25313
In the tutorials for ASP.Net MVC, the LINQ to Entities code looks like:
public class MyController : Controller
{
private Models db;
public ActionResult Index()
{
db = new Models();
var foo = (from f in db.foo select f).ToList();
return View(foo);
}
}
I'm guessing this has something to do with thread safety/connection pooling, but I just wanted to know if anyone knew of any good reasons not to do it this way:
public class MyController : Controller
{
private readonly Models db = new Models();
public ActionResult Index()
{
var foo = (from f in db.foo select f).ToList();
return View(foo);
}
}
Upvotes: 4
Views: 338
Reputation: 20924
I just put together a tip that covers this in quite a lot of detail.
Your educated guess of threading is just one of the many reasons why it is generally better to construct/dispose of the Context in the method that needs it.
There are some situations where this rule of thumb doesn't hold but they are pretty rare.
See this: Tip 18 - How to decide on a lifetime for your ObjectContext
Upvotes: 4
Reputation: 2030
Keeping it inside the method ensures that the db will only be instantiated when its needed and added to the connection pool when needed as well. I would even take the next step and instantiate it inside a using statement.
public class MyController : Controller
{
public ActionResult Index()
{
using (Models db = new Models())
{
var foo = (from f in db.foo select f).ToList();
return View(foo);
}
}
}
Upvotes: 1
Reputation: 40245
From the code samples I've seen you should write the code your looking for as follows:
public class MyController : Controller{
public ActionResult Index()
{
using (var db = new Models())
{
var foo = db.Foo.ToList();
return View(foo);
}
}
}
There are two main changes here.
Although you should consider your application architecture as a whole and think about abstracting your data access outside of your controller.
Upvotes: 1
Reputation: 5161
the first code snippet shouldn't compile. you are assigning a readonly field in a method that is not a constructor. are you sure it's an MVC sample?
Upvotes: 0