I have a problem while accessing a association object from linq to sql. I have a class Article and User. Each Article has a seller (which is a User) and each user has many Articles. I solved that with an association.
This is how my linq to sql classes looks like:
And this is the association:
Here is the code behind the 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
{
...
}
}
Now, when I want to get the Seller of an Article, I get the following error:
Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.
The error occurs in the get of seller.
Any ideas how to handle this?
EDIT: Heres' the code where DataContext is used:
public static List<Article> Read()
{
using (uDataContext dbx = new uDataContext())
{
return dbx.Article.ToList();
}
}
The list is used as following:
List<Article> articles = ArticleDALC.Read();
foreach (Article article in articles)
{
// Exception appears here!
User seller = article.Seller;
....
}
Solution found:
Simply set the DeferredLoadingEnabled
property on false when using the DataContext:
public static List<Article> Read()
{
using (uDataContext dbx = new uDataContext())
{
dbx.DeferredLoadingEnabled = false;
return dbx.Article.ToList();
}
}
Don't dispose your DataContext.
All LINQ objects are associated with a DataContext. You're probably accessing the object outside the using
block where the DataContext is created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With