实体框架懒加载无法从其他线程工作

实体框架懒加载无法从其他线程工作

本文介绍了实体框架懒加载无法从其他线程工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现延迟加载实体框架只能从创建的的ObjectContext 线程工作。为了说明问题,我做了一个简单的测试,包含仅有2实体一个简单的模型:地址。这里的code:

I just found out that lazy loading in Entity Framework only works from the thread that created the ObjectContext. To illustrate the problem, I did a simple test, with a simple model containing just 2 entities : Person and Address. Here's 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);
                    });
            }
        }
    }

TestSingleThread 法正常工作,在地址属性延迟加载。但在 TestMultiThread ,我收到了的NullReferenceException p2.Address.City ,因为 p2.Address 为null。

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

这是一个错误?这是它应该工作的方式?如果是这样,是否有任何文件提呢?我找不到MSDN上或谷歌的主题什么...

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...

和更重要的是,有没有解决办法? (除显式调用 LoadProperty 从辅助线程...)

And more importantly, is there a workaround ? (other than explicitly calling LoadProperty from the worker thread...)

任何帮助将是非常美联社preciated

Any help would be very appreciated

PS:我使用VS2010,所以它的EF 4.0。我不知道这是否是EF的previous版本相同...

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...

推荐答案

这设计是?是;任何调用加载,隐性或显性的,最终会通过的ObjectContext 和。

Is this by design? Yes; any call to Load, implicit or explicit, will eventually go through the ObjectContext, and ObjectContext is documented to be not thread-safe.

一个可能的解决方法是从工作线程对象上下文脱离实体并将其附加到对象上下文在当前线程。

A possible workaround would be to detach the entity from the object context in the worker thread and attach it to an object context in the current thread.

这篇关于实体框架懒加载无法从其他线程工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:09