c# - 我正在使用 linq,但收到错误 "There is already an open datareader associated with this command which must be closed first"

标签 c# .net linq

dc.Accounts.Where(a => blogs.Select(b => b.AccountID).Distinct()
           .Contains(a.AccountID));
foreach (Blog blog in blogs)
{
    blog.Account = accounts.Where(a => a.AccountID == blog.AccountID)
                           .FirstOrDefault();

    //this is done to access account outside ObjectContext
    blog.account = blog.Account;
}

在此代码中,我在 foreach 循环博客之前获取值,但随后出现错误

There is already an open datareader associated with this command which must be closed first.

最佳答案

这通常是当您有外部查询和内部查询并且外部查询仍在运行时引起的。通常,您可以通过强制外部查询完成来解决此问题;只需添加 ToList() 通常就足够了:

var blogs = dc.Accounts.Where(a => blogs.Select(b => b.AccountID).Distinct()
       .Contains(a.AccountID)).ToList(); // <======= here

关于c# - 我正在使用 linq,但收到错误 "There is already an open datareader associated with this command which must be closed first",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7185661/

相关文章:

c# - .NET 框架中是否有任何内置的依赖注入(inject)容器

.net - 多个部分意味着模型错误在表格之间流血

c# - 具有动态类型的 LINQ 查询字段<T>

.net - string.empty 和 isNullOrEmpty 之间的区别?

c# - 如何创建一个可以从多个数据源提取数据的 IQueryable Web API?

c# - Sql查询到linq的转换

c# - 代码隐藏更新 web.config 映射问题

c# - 将一些属性和一些逻辑混搭在一起

c# - 只有数字的文本框

c# - resx 中的 json 文件是二进制文件而不是文本文件