Search code examples
c#linq-to-sqlobjectdisposedexception

Cannot access a disposed object. Object name: 'DataContext accessed after Dispose


The title is the exception that is thrown after I access joined objects after generating the data with the following method using LINQ2SQL:

public static bool Get(int skip, int take, ListSortDirection direction, out List<Post> posts)
{
    bool result;

    using (var db = new MyDataContext())
    {
        try
        {
            posts = db.Posts
                .Where(p => !p.IsDeleted)
                .OrderBy(p => p.DateTimeCreated, direction)
                .Skip(skip)
                .Take(take)
                .ToList();
            result = true;
        }
        catch (Exception)
        {
            // Log the exception
            posts = new List<Post>();
            result = false;
        }
    }

    return result;
}

Below is an example of the join object that I'm referring to. In the method above, I'm selecting a collection of posts and the userprofileID of the Userprofile table is joined (in the .dbml and the database server) to the UserprofileID of the Post table.

The problem is that when I examine the collection of posts generated, the linked Userprofile returns the following exception:

new System.Collections.Generic.Mscorlib_CollectionDebugView(posts).Items[0].Userprofile' threw an exception of type 'System.ObjectDisposedException'

I've tried disabling the DeferredLoadingEnabled attribute in the datacontext and using DataLoadOptions:

var dlo = new DataLoadOptions();
dlo.LoadWith<Post>(p => p.Userprofile);
db.LoadOptions = dlo;

Which resulted in the same exception;

enter image description here Is there anything else I should be looking at?

Thanks!


Solution

  • Figured it out. In the onCreate event handler in a partial version of the datacontext, I added the DataLoadOptions. Not sure why it wasn't working in the method (fat fingers maybe) but here's what I came up with.

    public partial class MyDataContext 
    {
        partial void OnCreated()
        {
            var options = new DataLoadOptions();
    
            options.LoadWith<Vote>(v => v.Post);
            options.LoadWith<Vote>(v => v.Userprofile);
    
            LoadOptions = options;                    
        }
    }
    

    ... and to the folks who voted me down twice without leaving a comment - do me a favor and grow a pair.