错误:已经有一个用此命令,必须先关闭相关联的打开的DataReader [英] Error: There is already an open DataReader associated with this Command which must be closed first

查看:86
本文介绍了错误:已经有一个用此命令,必须先关闭相关联的打开的DataReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是SQL连接来访问不同的表在我的数据库。然而,code返回我下面的错误。

I'm using a sql connection to access to different tables in my database. However the code returns me the below error.

错误: 已经有与此命令必须先关闭相关联的打开的DataReader

Error : "There is already an open DataReader associated with this Command which must be closed first":

MyContext conn = new MyContext()

protected void ChangeName(int id)
{
    User user = conn.MyOtherTable.First(x => x.id == id);

    var elements = conn.MyTable.Where(x => x.id == id && x.name == name).OrderBy(x => x.id).OrderBy(x => x.name).
                    .Select(t => new { t.id, t.name, }).GroupBy(t => new { t.id, t.name, });

                foreach (var item in elements)
                {
                    foreach (var row in item)
                    {
                        for (int j = 1; j <= 5; j++)
                        {
                            if (row.name == "name")
                            {
                                user.name1 = row.name;
                                conn.SaveChanges();
                            }
                            if (row.name == "name2")
                            {
                                user.name2 = row.name;
                                conn.SaveChanges();
                            }
                         }
                     }
            }
 }


推荐答案

LINQ(交谈数据库时)通常是一个非缓冲假脱机的API。要做到你想要什么,或者:

LINQ (when talking to a database) is usually a non-buffered spooling API. To do what you want, either:


  • 启用多个活动结果集(MARS)

  • 第一缓冲数据

我preFER第二个选项;它只是涉及添加 .ToList()来您的第一行:

I prefer the second option; it just involves adding .ToList() to your first line:

var elements = conn.MyTable.Where(x => x.id == id && x.name == name)
        .OrderBy(x => x.id).OrderBy(x => x.name).
        .Select(t => new { t.id, t.name, }).GroupBy(t => new { t.id, t.name, })
        .ToList();

现在的后,这条生产线运行,我们知道我们已经在内存中的所有数据和读者已经关闭; previously它仍然是从读者交谈行输入。

now after this line has run we know we already have all the data in memory and the reader has closed; previously it could still have been talking row input from the reader.

有关完整性,使火星是这里讨论 - 这不会是我的建议,虽然。

For completeness, enabling MARS is discussed here - it wouldn't be my recommendation, though.

这篇关于错误:已经有一个用此命令,必须先关闭相关联的打开的DataReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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