操作无法完成,因为的DbContext已被释放错误 [英] The operation cannot be completed because the DbContext has been disposed error

查看:5308
本文介绍了操作无法完成,因为的DbContext已被释放错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的EF和我试图使用从我的数据库类型转换的扩展方法用户来我的信息类的UserInfo

我第一次使用数据库,如果有差别?



我的代码下面给出了错误




的操作不能因为的DbContext已处置完毕。




 
{
IQueryable的<使用者>用户;
使用(VAR的DataContext =新的DataContext())
{
用户= dataContext.Users
。凡(X => x.AccountID ==帐户ID和放大器;&安培; X .IsAdmin ==假);
如果(users.Any()==假)
{
返回NULL;
}
}
返回users.Select(X => x.ToInfo())了ToList(); //此行是问题
}
赶上(异常前)
{
// ...
}

我可以看到为什么它会做到这一点,但我也搞不懂为什么where语句不被保存到的结果的用户对象?



所以我想我的主要问题是,为什么没有工作,其次什么是正道使用扩展方法和EF?


解决方案

此的问题与放大器;答案使我相信的IQueryable需要其操作的积极方面。这意味着你应该试试这个:

 
{
IQueryable的<使用者>用户;

使用(VAR的DataContext =新的DataContext())
{
用户= dataContext.Users.Where(X => x.AccountID ==帐户ID和放大器;&安培; X .IsAdmin ==假);

如果(users.Any()==假)
{
返回NULL;
}
,否则
{
返回users.Select(X => x.ToInfo())。了ToList(); //此行是问题
}
}


}
赶上(异常前)
{
..
}


I'm new to EF and I'm trying to use an extension method which converts from my Database type User to my info class UserInfo.
I'm using database first if that makes a difference?

My code below gives the error

The operation cannot be completed because the DbContext has been disposed.

try
{
    IQueryable<User> users;
    using (var dataContext = new dataContext())
    {
        users = dataContext.Users
                  .Where(x => x.AccountID == accountId && x.IsAdmin == false);
        if(users.Any() == false)
        {
            return null;
        }
    }
    return users.Select(x => x.ToInfo()).ToList(); // this line is the problem
}
catch (Exception ex)
{
    //...
}

I can see why it would do it, but I also don't understand why the result of the where statement isn't being saved into the users object?

So I guess my main question is why doesn't it work and secondly what's the right way of using extension methods and EF?

解决方案

This question & answer lead me to believe that IQueryable require an active context for its operation. That means you should try this instead:

try
{
    IQueryable<User> users;

    using (var dataContext = new dataContext())
    {
        users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);

        if(users.Any() == false)
        {
            return null;
        }
        else
        {
            return users.Select(x => x.ToInfo()).ToList(); // this line is the problem
        }
    }


}
catch (Exception ex)
{
    ...
}

这篇关于操作无法完成,因为的DbContext已被释放错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆