0

I've built a WPF application using Entity Framework. My data store consists of hierarchical data (one project, with multiple different children entities).

To date I've been using a singleton pattern for my Context, as this allows me to have a global navigation tree in my UI (which then lazy loads as the user chooses to expand a specific parent to show its children). This has been working great up until now, but I'm now running into the dreaded exception:

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

I understand that I'm seeing this exception due to some actions being performed on some entities and simultaneous requests being made to load other entities, all from the same singleton context.

I further understand that it's best practice to keep a context as short-lived as possible. However, how will this be possible if I want the user to be able to see the whole project and make changes to some entities at a time? I'm at a complete loss as to how to have this global navigation tree in place with a short-lived context (as I keep running into the 'context has been disposed' problem).

Should I implement some locking mechanism around the context, or worse still, have this locking mechanism check each property before requesting it from the context? What is the recommended best practice for this scenario?

1 Answer 1

1

Correct, DbContext instances are cheap (they're just wrappers around pooled database connections).

If you want to maintain entities between persistence operations then you can detach and reattach entities to the new DbContext instance:

See https://msdn.microsoft.com/en-us/data/jj592676.aspx

FooEntity fromPreviousContext = ...

using (DbContext context = new DbContext()) 
{ 
    context.Foos.Attach( fromPreviousContext ); 
    context.SaveChanges(); 
}

A side-note: generally the Singleton pattern is considered by many to be an anti-pattern as it is easy to be misused especially when a singleton instance is being used to store contextual data - it becomes just a slightly more polite approach to global-variables. You might want to consider the Context pattern instead (unrelated to DbContext).

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

Comments

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.