Search code examples
c#databaselinqdisposelifecycle

DataContext accessed after Dispose in render pages/controls


I'm randomly getting "DataContext accessed after Dispose" errors but only on aspx and ascx pages/controls. Is there a general rule that I shouldn't be calling methods inline on pages that use datacontexts?

I'm presuming by the time the page renders and calls the method the datacontext has already been disposed?

e.g. on default.aspx

<%= CurrentContent.GetText("Intro") %>

CurrentContent is actually a database object referred to in default.aspx.cs


Solution

  • assuming you are using it like this

    using (MyDbContext ctx = new MyDbContext())
    {
        return from r in ctx.Table select r;
    }
    

    Deferred execution is what is happening to you. That query does not execute right then and there, and is only running when the returned enumerator is finally used - which in this case, is after the using block disposes of your context. If you want to be sure this doesn't happen, either change your query pattern to

    using (MyDbContext ctx = new MyDbContext())
    {
        return (from r in ctx.Table select r).ToList();
    }
    

    or change your disposal methods. I tend to like tying the lifetime of my context to the enclosing object, which in your case would be the ASP.NET Page object. Make the context a member variable and dispose of it in the Page.Dispose