Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework lazy loading doesn't work from other thread
    text
    copied!<p>I just found out that lazy loading in Entity Framework only works from the thread that created the <code>ObjectContext</code>. To illustrate the problem, I did a simple test, with a simple model containing just 2 entities : <code>Person</code> and <code>Address</code>. Here's the code :</p> <pre><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 =&gt; { Console.WriteLine("{0} lives in {1}.", p2.Name, p2.Address.City); }); } } } </code></pre> <p>The <code>TestSingleThread</code> method works fine, the <code>Address</code> property is lazily loaded. But in <code>TestMultiThread</code>, I get a <code>NullReferenceException</code> on <code>p2.Address.City</code>, because <code>p2.Address</code> is null.</p> <p>It that a bug ? Is this the way it's supposed to work ? If so, is there any documentation mentioning it ? I couldn't find anything on the subject on MSDN or Google...</p> <p>And more importantly, is there a workaround ? (other than explicitly calling <code>LoadProperty</code> from the worker thread...)</p> <p>Any help would be very appreciated</p> <p>PS: I'm using VS2010, so it's EF 4.0. I don't know if it was the same in the previous version of EF...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload