Search code examples
asp.net-mvcentity-frameworkasp.net-mvc-4using

Disposing Database context with using statement in MVC


I'm using entity framework in my MVC website and I'm disposing my database context using using-statement. Now my question is if I close using statement after return, would the database context disposed properly or not. Ex:

 public ActionResult SomeAction(){

      using (var DB = new DatabaseContext()){

       ....           

       return View();                
      }
 }

Do I have to close the using statement before return? Or it would be disposed properly in the way I'm using it.


Solution

  • Do I have to close the using statement before return? Or it would be disposed properly in the way I'm using it?

    It will be automagically disposed for you. You can refer to this answer for more information .The Dispose method is called however the using statement is executed, unless it was an abrupt whole-process termination. The most common cases are:

    • A return within the block
    • An exception being thrown (and not caught) within the block
    • Reaching the end of the block naturally

    Basically a using statement is mostly syntactic sugar for a try/finally block - and finally has all the same properties.

    From section 8.13 of the C# 4 specification:

    A using statement is stranslated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource.