由于DbContext处理错误,操作无法完成 [英] The operation cannot be completed because the DbContext has been disposed error

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

问题描述

我是EF的新手,我试图使用一个扩展方法,它从我的数据库类型 User 转换到我的信息类 UserInfo

如果有差异,我先使用数据库?



我的代码如下给出错误


由于DbContext已被处理,操作无法完成。




  try 
{
IQueryable< User>用户;
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(); //这行是问题
}
catch(Exception ex)
{
// ...
}

我可以看到为什么会这样做,但是我也不明白为什么where语句的结果没有被保存到用户对象?



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

解决方案

这个

  try 
{
IQueryable< User>用户;

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

if(users.Any()== false)
{
return null;
}
else
{
return users.Select(x => x.ToInfo())ToList(); //这行是问题
}
}


}
catch(Exception ex)
{
..
}


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天全站免登陆