由于DbContext处理错误,操作无法完成 [英] The operation cannot be completed because the DbContext has been disposed error
问题描述
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?
这个 I'm new to EF and I'm trying to use an extension method which converts from my Database type My code below gives the error The operation cannot be completed because the DbContext has been disposed.
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 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:
这篇关于由于DbContext处理错误,操作无法完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
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)
{
..
}
User
to my info class UserInfo
.
I'm using database first if that makes a difference?
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)
{
//...
}
users
object?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)
{
...
}