Question

I have been having some strange errors with Entity Framework calls, and I am exploring the possibility they are due to concurrent multi-threaded access using the same ObjectContext.

I have tried to create a new context for every thread by putting the creation context inside ThreadLocal.

private System.Threading.ThreadLocal<EF.XYZEntities> threadLocalContext = new System.Threading.ThreadLocal<EF.XYZEntities>(() => new EF.XYZEntities(connectionString));
private EF.XYZEntities context { get { return threadLocalContext.Value; } }

This is not working. The first use of that context throws an error:

Invalid object name 'dbo.Site'.

How can I get this to work?

Was it helpful?

Solution

Using a shared context is generally considered 'bad', unless you micro manage everything very well. Using shared contexts that are not managed well can produce very strange results.

It's generally best practice to take a Unit of Work approach with the context as follows:

using (DBEntities ctx = new DBEntities())
{
    // Explicitly open the context connection yourself - to help prevent connection pooling / sharing
    // The connection will automatically be closed once exiting the using statement,  
    // but it won't hurt to put a ctx.Connection.Close(); after everything inside the using statement.
    ctx.Connection.Open();

    // Do Stuff

    // If necessary ctx.SaveChanges();
    // Not necessary but you could put a ctx.Connection.Close() here, for readability if nothing else.
}

UPDATE: In reply to Noseratio's comment below about async and EF. Taken from here

Non-Goals

The following are things we are explicitly not trying to enable with the feature in EF6:

  • Thread safety
  • Async lazy loading

Thread Safety

While thread safety would make async more useful it is an orthogonal feature. It is unclear that we could ever implement support for it in the most general case, given that EF interacts with a graph composed of user code to maintain state and there aren't easy ways to ensure that this code is also thread safe.

For the moment, EF will detect if the developer attempts to execute two async operations at one time and throw....

Async support in EF requires .NET 4.5 and will not be available on .NET 4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top