首页 文章

无法访问已处置的对象 . 对象名:'Dispose后访问的DataContext

提问于
浏览
1

Headers 是在使用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;
}

下面是我所指的连接对象的示例 . 在上面的方法中,我选择了一组帖子,并将Userprofile表的userprofileID连接(在.dbml和数据库服务器中)到Post表的UserprofileID .

问题是,当我检查生成的帖子集合时,链接的Userprofile会返回以下异常:

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

我已经尝试在datacontext中禁用DeferredLoadingEnabled属性并使用DataLoadOptions:

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

这导致了同样的例外;

enter image description here
还有什么我应该看的吗?

谢谢!

1 回答

  • 0

    弄清楚了 . 在datacontext的部分版本中的onCreate事件处理程序中,我添加了DataLoadOptions . 不知道为什么它没有在这个方法中工作(胖手指也许)但是这就是我想出来的 .

    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;                    
        }
    }
    

    ......对于那些在没有发表评论的情况下投票给我两次的人 - 帮我一个忙,然后成长一对 .

相关问题