Why data is not found after calling SqlDataReader.NextResult?

My problem is that this does not work;

while (reader.Read())
{
   if (reader.NextResult() == true)
   {
      json.AppendFormat("{{\"AvgDate\": \"{0}\"}},{{\"MarkerID\": \"{1}\"}},", reader["AvgDate"], reader["MarkerID"]);
   }

But it works;

while (reader.Read())
{
    json.AppendFormat("{{\"AvgDate\": \"{0}\"}},{{\"MarkerID\": \"{1}\"}},", reader["AvgDate"], reader["MarkerID"]);
}

The problem with the first is that the reader does not find any data to read. I got;

"Invalid read attempt when no data is present."

Can anyone understand why?

+3
source share
3 answers

NextResult () forces the reader to move on to the next set of results returned from the request. As you wrote it, it will skip the first set of results (most likely the only one).

I think you need a template:

if (reader.HasRows)
{
     do
     {
        while (reader.Read())
        {
             ...
        }
     }
     while (reader.NextResult());
}

, - , , , .

EDIT: :

JSON , DataContractJsonSerializer:

 public class DateClass
 {
      public string AvgDate { get; set; }
      public int MarkerID { get; set; }
 }

 ...

 var dates = new List<DateClass>();
 if (reader.HasRows)
 {
       while (reader.Read())
       {
           var date = new DateClass { AvgDate = reader["AvgDate"].ToString(), MarkerID = (int)reader["MarkerID"] };
            dates.Add( date );
       }
 }

 var stream = new MemoryStream();
 var serializer = new DataContractJsonSerializer( typeof(DateClass) );
 serializer.WriteObject( stream, dates );
 stream.Seek( 0, SeekOrigin.Begin );
 return stream.ToString();
+16

NextResult Reader. , .

+4

tvanfosson :

if (reader.HasRows) 
{
     do
     {
        while (reader.Read())
        {
         ...
        }
     }
     while (reader.NextResult());
}

:

do
{
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            ...
        }
    }
} while (reader.NextResult());

, , . , , .

, , HasRows.

+3

Source: https://habr.com/ru/post/1733977/


All Articles