Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot access a disposed object"

Tags:

c#

linq-to-sql

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: linq to sql classes

And this is the association:

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;
    ....
}
like image 893
Nagelfar Avatar asked Feb 03 '13 18:02

Nagelfar


Video Answer


2 Answers

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();
    }
}
like image 66
Nagelfar Avatar answered Nov 24 '22 23:11

Nagelfar


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.

like image 26
zmbq Avatar answered Nov 24 '22 23:11

zmbq