1

I have this class and i often(but not always) get NullReferenceException or ObjectDisposedException when use method ExecuteQuery:

public class Dao
{
    protected StoreDbContext Context = new StoreDbContext();

    public IEnumerable<T> ExecuteQuery<T>(string query, params object[] parameters)
    {
        return  Context.Database.SqlQuery<T>(query, parameters).ToList();
    }

}

but, if if i will create Context in method i don't get any exception. Why?

public class Dao
{
    protected StoreDbContext Context = new StoreDbContext();

    public IEnumerable<T> ExecuteQuery<T>(string query, params object[] parameters)
    {
        return  new StoreDbContext().Database.SqlQuery<T>(query, parameters).ToList();
    }

}

1 Answer 1

4

Don't keep the StoreDbContext hanging around when doing updates. It will end up with stale data/entities in it. The accepted pattern is to fire up a new Context for a unit of work/scoped set of operations. The second example might be acceptable, but you need to ensure you dispose of the context by creating it with a using statement. Refactor the method to account for this.

I tend to keep search results in a separate context with no tracking (read only) but would use a fresh context for updates, as I'm using WCF Data Services.

Sign up to request clarification or add additional context in comments.

3 Comments

The second example wouldn't be right either: the newly created context never gets disposed. Fixing that by disposing the context inside ExecuteQuery could be problematic since the returned objects may be referring to that context, so the context would be disposed too early.
@hvd I agree about disposing, but the ToList() is returning a completely new variable so a return of the list within the using statement should be perfectly acceptable
The list is a completely new object, but the objects contained in that list may, depending on the type, keep references to the context (for example, for lazy loading, or change tracking). You say "with no tracking", and you're right, then it's no problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.