从 linq 到 sql 访问关联对象时遇到问题。 我有一个类文章和用户。每篇文章都有一个卖家(即用户),每个用户都有很多篇文章。我通过协会解决了这个问题。
这是我的 linq to 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.'.
卖家获取错误。
任何想法如何处理这个?
编辑:这是使用 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/