Entity Framework local loading does not work from another topic

I just found out that lazy loading in the Entity Framework only works from the thread that created the ObjectContext . To illustrate the problem, I made a simple test with a simple model consisting of only two objects: Person and Address . Here is the code:

  private static void TestSingleThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Console.WriteLine("{0} lives in {1}.", p.Name, p.Address.City); } } } private static void TestMultiThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Person p2 = p; // to avoid capturing the loop variable ThreadPool.QueueUserWorkItem( arg => { Console.WriteLine("{0} lives in {1}.", p2.Name, p2.Address.City); }); } } } 

The TestSingleThread method works fine, the Address property loads lazily. But in TestMultiThread I get a NullReferenceException on p2.Address.City , because p2.Address is null.

This is mistake? So should it work? If so, are there any documents? I could not find anything on this subject on MSDN or Google ...

And more importantly, is there a workaround? (except for explicitly calling LoadProperty from the workflow ...)

Any help would be much appreciated

PS: I am using VS2010, so it is EF 4.0. I don't know if it was the same in the previous version of EF ...

+7
multithreading c # entity-framework lazy-loading
source share
1 answer

Is it for design? Yes; any Load call, implicit or explicit, will eventually go through the ObjectContext , and the ObjectContext is documented as unsafe .

A possible workaround would be to detach the object from the context of the object in the workflow and attach it to the context of the object in the current thread.

+7
source share

All Articles