【问题标题】:LINQ 2 SQL Query ObjectDisposed ExceptionLINQ 2 SQL 查询 ObjectDisposed 异常
【发布时间】:2011-12-23 22:10:38
【问题描述】:

我今天的这个很奇怪。

我在汇编方法中有这个查询。

        public Order[] SelectAllOrders()
    {
        Order[] orders;
        using (MyDataContext context = new MyDataContext())
        {
            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Order>(order => order.OrderDetails);
            context.LoadOptions = dlo;

            orders = context.Orders.Select(p => p).ToArray();
        }
        return orders;
    }

假设我已经调用了 SQL 命令执行的 ToArray() 并给了我我需要的对象,我将它们给了一个新的 Order[] 数组,这不应该需要 DataContext 实例。 在我序列化从方法返回得到的 Order[] 时,序列化程序尝试再次访问 DataContext,我得到一个无法访问已处理对象的异常。

在没有 using() 语句的情况下进行了尝试,并且可以正常工作。但是,为什么我会得到这种行为? 任何人都可以解释为什么在我调用 .ToArray() 并用内容分配新变量时延迟加载仍然存在?

【问题讨论】:

    标签: linq-to-sql c#-3.0


    【解决方案1】:

    Select(p=&gt;p) 收效甚微;您不妨致电:

    orders = context.Orders.ToArray();
    

    是问题所在——我猜OrderDetails 没有真正加载,或者它正在尝试延迟加载一些 other 数据。我建议通过(在开发会话中)进行调查:

        Order[] orders;
        using (MyDataContext context = new MyDataContext())
        {
            context.Log = Console.Out; // show me
            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Order>(order => order.OrderDetails);
            context.LoadOptions = dlo;
            Console.WriteLine("> Calling ToArray");
            orders = context.Orders.ToArray();
            Console.WriteLine("> ToArray complete");
    
            // TODO: your extra code that causes serialziation, probably
            // involving `DataContractSerializer`
    
            Console.WriteLine("> Calling Dispose");
        }
    

    有了这个,您应该能够看到发生在ToArray之前Dispose() 的任何额外的数据库访问。重点是:序列化需要这些数据,所以要么 a:确保它被加载,要么 b:从序列化中排除它。

    【讨论】:

    • Marc,谢谢你的回答,我不记得如何在输出窗口中显示 SQL 查询以避免控制台项目测试,还没有找到它:P。所以,创建了控制台,你是对的,我很愚蠢地忘记了关联 OrderDetails 1 - * Product。答案是 LoadWith(od => od.Product) 一切都很好。谢谢……
    猜你喜欢
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多