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;
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 ...
multithreading c # entity-framework lazy-loading
Thomas levesque
source share