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.
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:
return
within the blockBasically 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 atry
statement that includes afinally
clause. Thisfinally
clause disposes of the resource.