Search code examples
entity-framework-4.1idisposabledbcontextasp.net-mvc-scaffolding

MvcScaffolding creates disposable resources that are not disposed


Using MvcScaffolding with EF4.1, I see that the first generated line of a Controller generally is the following field definition:

public class FooController : Controller
{
    private BarContext context = new BarContext();
    //.....

where BarContext is as follows:

 public class BarContext : System.Data.Entity.DbContext

Given that System.Data.Entity.DbContext implements IDisposable, I am surprised not to find any generated override in FooController for the Dispose(bool) method that might take care of disposing context.

Is this an oversight in the templates, or is there something I'm missing that makes this a non-issue?


Solution

  • No, you are not missing anything, you do need to override Dispose, as described in this EF tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application The built-in scaffolding in MVC 3 Tools Update does generate the override (pre-release versions did not but the released version does), as noted in the tutorial. If the NuGet MvcScaffolding package does not do it, that is an oversight.