There a lot of code blocks like this:
public class SomeController : Controller
{
DbEntities entity = new DbEntities();
public ActionResult Add()
{
entity.someOperations...
return View();
}
public ActionResult Edit()
{
entity.someOperations...
return View();
}
public ActionResult Detail()
{
entity.someOperations...
return View();
}
public ActionResult Detail()
{
entity.someOperations...
return View();
}
.....
Should I change the methods like this?:
public class SomeController : Controller
{
public ActionResult Add()
{
using(DbEntities entity = new DbEntities())
{
entity.someOperations...
}
return View();
}
.....
What are the problems with not using using-statement in EF? OR what is the best way? Also, If we use using-statement code blocks are grown.
Thanks...
There's no big problem in your example above if using using-statement but it's very hard to write unit tests for code like that, when dbContext is a local variable.
If you don't follow any design pattern like Repository, Unit of Work, you don't want to write unit test, then wrap all logic in using statement is the best choice in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With