Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawbacks with using entity framework without using statement?

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...

like image 566
AliRıza Adıyahşi Avatar asked Jul 03 '26 03:07

AliRıza Adıyahşi


1 Answers

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.

like image 65
phnkha Avatar answered Jul 04 '26 16:07

phnkha