阅读器关闭时调用 FieldCount 的尝试无效

发布于 2024-09-14 04:25:36 字数 1707 浏览 2 评论 0原文

当我尝试对从数据库收到的数据执行 dataReader.Read 时,会发生上述错误。我知道那里有两行,所以它不是,因为实际上不存在数据。

是否是 CommandBehavior.CloseConnection 导致了问题?有人告诉我你必须在 ExecuteReader 之后立即执行此操作?这是正确的吗?

        try
        {
            _connection.Open();
            using (_connection)
            {
                SqlCommand command = new SqlCommand("SELECT * FROM Structure", _connection);
                SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

                if (dataReader == null) return null;

                var newData = new List<Structure>();
                while (dataReader.Read())
                {
                    var entity = new Structure
                    {
                        Id = (int)dataReader["StructureID"],
                        Path = (string)dataReader["Path"],
                        PathLevel = (string)dataReader["PathLevel"],
                        Description = (string)dataReader["Description"]
                    };

                    newData.Add(entity);
                }
                dataReader.Close();

                return newData;
            }
        }
        catch (SqlException ex)
        {
            AddError(new ErrorModel("An SqlException error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        catch (Exception ex)
        {
            AddError(new ErrorModel("An error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        finally
        {
            _connection.Close();
        }
    }

预先感谢您的任何帮助。

克莱尔

The error above occurs when I try to do a dataReader.Read on the data recieved from the database. I know there are two rows in there so it isnt because no data actually exists.

Could it be the CommandBehavior.CloseConnection, causing the problem? I was told you had to do this right after a ExecuteReader? Is this correct?

        try
        {
            _connection.Open();
            using (_connection)
            {
                SqlCommand command = new SqlCommand("SELECT * FROM Structure", _connection);
                SqlDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection);

                if (dataReader == null) return null;

                var newData = new List<Structure>();
                while (dataReader.Read())
                {
                    var entity = new Structure
                    {
                        Id = (int)dataReader["StructureID"],
                        Path = (string)dataReader["Path"],
                        PathLevel = (string)dataReader["PathLevel"],
                        Description = (string)dataReader["Description"]
                    };

                    newData.Add(entity);
                }
                dataReader.Close();

                return newData;
            }
        }
        catch (SqlException ex)
        {
            AddError(new ErrorModel("An SqlException error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        catch (Exception ex)
        {
            AddError(new ErrorModel("An error has occured whilst trying to return descendants", ErrorHelper.ErrorTypes.Critical, ex));
            return null;
        }
        finally
        {
            _connection.Close();
        }
    }

Thanks in advance for any help.

Clare

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

墟烟 2024-09-21 04:25:36

您的代码,如图所示,没有问题。我已将其纳入测试项目,并且有效。目前尚不清楚为什么您会通过上面显示的代码收到此消息。以下是一些调试技巧/建议。我希望它们对您有价值。

  • while (dataReader.Read()) 上创建断点。在进入代码块之前,请在“立即”或“监视”窗口中输入:dataReader.HasRows。其计算结果应为 true。

  • 当停在 Read() 上时,打开本地窗口以检查 dataReader 的所有属性。确保 FieldCount 符合您对 SELECT 语句的预期。

  • 当进入此 Read() 迭代时,是否创建了学生对象? dataReader["StructureID"] 以及立即窗口中的所有其他值的值是多少?

这不是导致问题的 CommandBehavior.CloseConnection 。这只是告诉连接在您关闭数据读取器时也自行关闭。

Your code, as displayed is fine. I've taken it into a test project, and it works. It's not immediately clear why you get this message with the code shown above. Here are some debugging tips/suggestions. I hope they're valuable for you.

  • Create a breakpoint on the while (dataReader.Read()). Before it enters its codeblock, enter this in your Immediate or Watch Window: dataReader.HasRows. That should evaluate to true.

  • While stopped on that Read(), open your Locals window to inspect all the properties of dataReader. Ensure that the FieldCount is what you expect from your SELECT statement.

  • When stepping into this Read() iteration, does a student object get created at all? What's the value of dataReader["StructureID"] and all others in the Immediate Window?

It's not the CommandBehavior.CloseConnection causing the problem. That simply tells the connection to also close itself when you close the datareader.

陌路黄昏 2024-09-21 04:25:36

当你在C#中使用Using时,在使用的最后一个}之后,连接会自动关闭,这就是为什么当你尝试读取他时,你会关闭fieldcount,因为这是不可能的,因为你想要这些数据,然后读取在关闭使用之前,或者您可以通过不使用(使用)手动打开和关闭连接

When you use the Using in C#, after the last } from the using, the Connection automatically close, thats why you get the fieldcount to be closed when u try to read him, as that is impossible, because u want those datas, read then before close the using, or u can open and close manually the connection, by not using the (using)

梦情居士 2024-09-21 04:25:36

当我收到该错误时,恰好是命令超时问题(我正在读取一些大型二进制数据)。作为第一次尝试,我增加了命令超时(不是连接超时!),问题得到了解决。
注意:在尝试找出问题时,我尝试监听 (Sql)connection 的 StateChanged 事件,但事实证明连接永远不会处于“断开”状态。

When I got that error, it happened to be a command timeout problem (I was reading some large binary data). As a first attempt, I increased the command timeout (not the connection timeout!) and the problem was solved.
Note: while attempting to find out the problem, I tried to listen to the (Sql)connection's StateChanged event, but it turned out that the connection never fall in a "broken" state.

梦纸 2024-09-21 04:25:36

这里同样的问题。测试了上述所有解决方案

  • 增加命令超时
  • 在读取后关闭连接

这是代码

    1 objCmd.Connection.Open()
    2 objCmd.CommandTimeout = 3000
    3 Dim objReader As OleDbDataReader = objCmd.ExecuteReader()
    4 repeater.DataSource = objReader
    5 CType(repeater, Control).DataBind()
    6 objReader.Close()
    7 objCmd.Connection.Dispose()

此外,在第 4 行 objReader has Closed = False

Same problem here. Tested all the above solutions

  • increase command timeout
  • close the connection after read

Here's the code

    1 objCmd.Connection.Open()
    2 objCmd.CommandTimeout = 3000
    3 Dim objReader As OleDbDataReader = objCmd.ExecuteReader()
    4 repeater.DataSource = objReader
    5 CType(repeater, Control).DataBind()
    6 objReader.Close()
    7 objCmd.Connection.Dispose()

Moreover, at line 4 objReader has Closed = False

寂寞美少年 2024-09-21 04:25:36

我在使用 VS.NET 调试器并尝试检查一些 IQueryable 结果时遇到此异常。错误的决定,因为 IQueryable 导致了大型表扫描。解决方法是停止并重新启动调试器并且不尝试预览此特定的 IQueryable。

I got this exception while using the VS.NET debugger and trying to examine some IQueryable results. Bad decision because the IQueryable resulted in a large table scan. Stopping and restarting the debugger and NOT trying to preview this particular IQueryable was the workaround.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文