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

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

问题描述

我是 EF 的新手,我正在尝试使用一种扩展方法,该方法将我的数据库类型 User 转换为我的信息类 UserInfo.
如果有区别,我会先使用数据库吗?

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

操作无法完成,因为 DbContext 已被释放.

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)
{
    //...
}

我明白为什么会这样做,但我也不明白为什么 where 语句的结果没有保存到 users 对象中?

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?

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

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?

推荐答案

这个问题&answer 让我相信 IQueryable 需要一个活动上下文来进行操作.这意味着你应该试试这个:

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