Search code examples
c#asp.net-mvcentity-frameworkusing

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


Solution

  • The using statement approach is the best of the two that you have proposed above. Using this approach, you can be assured that the ObjectContext is closed and disposed of after it's use.

    Using your other approach, one would assume that the ObjectContext could be left unclosed, therefore hogging connections to the database. To see this in action, try creating a sample app with your other approach, then profile it using the EFProfiler and watch the number of ObjectContext's opened rise, whilst the number of closures will be notably smaller.

    I recently worked on a project that was having database issues under high levels of usage that adopted your second pattern (you can see my question about it HERE). As I didn't have enough time on the project/code base was too large, I didn't have the option to switch to the using statement approach. Instead I implemented the following to manually force the disposal of the ObjectContext on the End_Request in Global.asax (I had an instance of the DbContext on a static instance of my BusinessLayerService:

    protected void Application_EndRequest(object sender, EventArgs e)
        {
            BusinessLayerService.Instance.Dispose();
            BusinessLayerService.Instance = null;
        }
    

    But if you have the option from the project start: I would highly recommend using the using pattern