c# - "Cannot access a disposed object"

标签 c# linq-to-sql

从 linq 到 sql 访问关联对象时遇到问题。 我有一个类文章和用户。每篇文章都有一个卖家(即用户),每个用户都有很多篇文章。我通过协会解决了这个问题。

这是我的 linq to sql 类的样子: linq to sql classes

这是关联:

association

这是 Article.Seller 背后的代码:

[global::System.Data.Linq.Mapping.AssociationAttribute(Name="User_Article", Storage="_Seller", ThisKey="SellerID", OtherKey="ID", IsForeignKey=true)]
public User Seller
{
    get
    {
        return this._Seller.Entity;
    }
    set
    {
                   ...
    }
}

现在,当我想获取文章的卖家时,出现以下错误:

Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.

卖家获取错误。

任何想法如何处理这个?

编辑:这是使用 DataContext 的代码:

public static List<Article> Read()
{
    using (uDataContext dbx = new uDataContext())
    {
        return dbx.Article.ToList();
    }
}

列表使用如下:

List<Article> articles = ArticleDALC.Read();

foreach (Article article in articles)
{
    // Exception appears here!
    User seller = article.Seller;
    ....
}

最佳答案

找到的解决方案:

使用 DataContext 时,只需将 DeferredLoadingEnabled 属性设置为 false:

public static List<Article> Read()
{
    using (uDataContext dbx = new uDataContext())
    {
        dbx.DeferredLoadingEnabled = false;
        return dbx.Article.ToList();
    }
}

关于c# - "Cannot access a disposed object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675582/

相关文章:

c# - Linq:将数据选择到多个列表中

c# - 如何在 dbml 中标记为可序列化?

web-services - 使用 join 在 linq 中检索 10 条记录

c# - 某些 linq2sql 生成的 T-SQL 出现问题

c# - 在 Entity Core 中使用 Postgres lpad

c# - 从后端加载日期数据设置引导日期选择器以正确的格式

c# - Javascript/ASP.NET MVC 4 - 在 Javascript 中使用 C# 字符串

c# - 分组和计数

c# - 如何使用CreateExternalTexture和从C++库传递的指针创建Texture2D?

c# - 在 getAsync 中为客户端添加 header (在 using block 中)