0

When using a using statement with the Entity Framework, does it dispose before the function returns?

For example, say I have something like this

public ActionResult test()
{
   using (var empDb = new empEntities())
  {
     var mod = (from emps in empDb.employees 
                select emps);
     return View(mod);
  }
}

Does the using statement dispose of the entities before the return View(mod); or is it still open until the view is closed?

user1314413
  • 103
  • 2
  • 14
  • Yes. You should materialize your model before passing it to the view. Passing a view an IQueryable is bad because, you're right, by the time the View is rendered, the context has been disposed. The view shouldn't be calling out to the database (which is what would happen if you pass it an IQueryable). You could use dependency injection to hand in a context that has request-scope life expectancy (I do this with ninject) and this problem would go away, but I still wouldn't feel comfortable handing an unmaterialized query to a view. – spender Feb 23 '17 at 17:06

1 Answers1

0

As a rule, when you use an IDisposable object, The using statement calls the Dispose method on the object in the correct way, and it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

manika
  • 187
  • 2
  • 13