加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – “无法访问已处置的对象”

发布时间:2020-12-15 18:13:41 所属栏目:百科 来源:网络整理
导读:从 linq到sql访问关联对象时遇到问题. 我有一篇文章和用户.每篇文章都有一个卖家(用户),每个用户都有很多文章.我通过协会解决了这个问题. 这是我的linq到sql类的样子: 这是协会: 以下是Article.Seller背后的代码: [global::System.Data.Linq.Mapping.Asso
从 linq到sql访问关联对象时遇到问题.
我有一篇文章和用户.每篇文章都有一个卖家(用户),每个用户都有很多文章.我通过协会解决了这个问题.

这是我的linq到sql类的样子:

这是协会:

以下是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.’.

错误发生在卖家的获取中.

任何想法如何处理这个?

编辑:Heres’使用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();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读