【发布时间】:2013-02-03 18:12:45
【问题描述】:
从 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
{
...
}
}
现在,当我想获取文章的卖家时,我收到以下错误:
无法访问已处置的对象。对象名称:'DataContext 已访问 处理后。'。
卖家获取时出错。
任何想法如何处理这个?
编辑:这是使用 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;
....
}
【问题讨论】:
-
这是因为数据来自的上下文被释放了。您需要显示执行 get 的代码。
-
感谢 cmets,我添加了获取代码!
标签: c# linq-to-sql