6

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

ClareBear
  • 1,493
  • 6
  • 25
  • 47

5 Answers5

3

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)

  • Agreed. The " using (_connection) {" is what is closing the datareader before you "consume" the datareader. Take out the "using" and keep the " CommandBehavior.CloseConnection "...and after you consume the datareader, make sure you call .Close() on it. – granadaCoder Apr 25 '14 at 14:58
2

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.

p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • 1
    You were right it wasn't the CommandBehavior.CloseConnection causing the issue. This masked the real issue - trying to convert a a datatype to thewrong thing. 'Invalid attempt to call FieldCount when reader is closed' only occurred when I stepped through my code (maybe because I took to long?) – ClareBear Aug 13 '10 at 09:18
  • Yes..this was the datatype issue..The datatype in the database were datetime2 and in the source code i was referring this field as string.. So i had to type cast the datetime2 field in the database to varchar(11) before getting. – Krishna Jun 21 '19 at 19:14
1

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.

Starnuto di topo
  • 3,215
  • 5
  • 32
  • 66
1

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

SimoneMSR
  • 368
  • 1
  • 6
  • 16
0

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.

CAK2
  • 1,892
  • 1
  • 15
  • 17