【问题标题】:Linq to SQL child table throwing Data Context Dispose issueLinq to SQL 子表抛出 Data Context Dispose 问题
【发布时间】:2016-05-10 19:53:51
【问题描述】:

我正在使用 Linq to SQL 类进行数据提取,并具有以下实体:

  • 客户 -> 订单

Customer 和 Order 通过 CustomerID 上的 FK 约束链接,并以这种关系出现在我的 .dbml 文件中

当我通过智能感知访问对象属性时,我可以看到 Customer.Name, Customer.Address 等,还可以看到链接的订单实体 Customer.Orders

我的问题是,当我查询数据库以仅填充 Customer 实体并处理 Datacontext 时,我得到一个错误抛出

无法访问已处置的对象。对象名称:'DataContext 已访问 处理后。'。

public IEnumerable<Customer> GetCustomer(Int32 customerID)
        {
            // initialise
            Customer cust = new Customer();

           using (CustomerManager ctl = new CustomerManager())
            {
                // get customer, this returns a single customer entity
                // i.e. datacontext.Customers.Where(m=> m.CustomerID == customerID).FirstOrDefault();
                cust = ctl.SelectCustomer(customerID);

            }

            yield return cust;
}

我已尝试将其更改为存储过程,即Customer_SelectResult,并且效果很好。这是我使用表格的时候。

有什么办法可以防止子表引起这个问题?

提前致谢

【问题讨论】:

  • 只是出于好奇,如果给定 id 只有一个客户,为什么要返回 IEnumerable
  • 是的,只有一个客户,但它仍然会抛出错误。

标签: c# json asp.net-mvc asp.net-web-api linq-to-sql


【解决方案1】:

在处理之前,您必须加载所有数据。请参阅https://msdn.microsoft.com/en-us/library/bb399393(v=vs.110).aspx 以获得解释和https://msdn.microsoft.com/en-us/library/bb386920(v=vs.110).aspx 以获得解决方案。

产生结果会产生另一个问题,当迭代结果时,会在数据库上执行查询。见https://blogs.msdn.microsoft.com/charlie/2007/12/10/linq-and-deferred-execution/

【讨论】:

  • 这是最近使用 MVC4.5 的吗?我在其他使用 Linq to SQL 的项目中没有遇到这个问题
  • 我不知道。但我猜由于代码结合使用了 yield 语句和 IEnumerable,所以查询是在上下文被释放后执行的。
  • 问题已通过设置 DeferredLoadingEnabled = false 解决;
【解决方案2】:

关键字using 会自动在其中释放已初始化的对象。我猜ctl 在调用GetCustomer 之后被释放。所以你可以尝试不使用它:

CustomerManager ctl = new CustomerManager()
yield return ctl.SelectCustomer(customerID);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多