Reputation: 447
I read data from my stored procedure. When I insert a breakpoint I get this situation:
The stored procedure returns one row with 8 columns. You can see this on a picture. But when I am trying to read one value:
var post_id = reader[4].ToString();
I got this exception:
Invalid attempt to read when no data is present.
My model:
public class Alarm
{
public long Id { get; set; }
public DateTime StartDate { get; set; }
public int Snoozes { get; set; }
public bool Repeat { get; set; }
public DateTime AlarmUpdateTime { get; set; }
public virtual User User { get; set; }
public virtual List<FacebookNotificationStatus> StatusUpdates { get; set; }
}
public class FacebookStatusUpdate
{
public long Id { get; set; }
public DateTime FacebookUpdateTime { get; set; }
public string PostId { get; set; }
public DateTime? FacebookPostTime { get; set; }
public DateTimeOffset ClientTime { get; set; }
public int Offset { get; set; }
public virtual FacebookNotificationStatus Status { get; set; }
public virtual Alarm Alarm { get; set; }
}
Can somebody help me?
Upvotes: 0
Views: 513
Reputation: 1062780
Dealing with all the subtleties of ADO.NET is not fun; frankly, I suspect you might find it easier to use something like "dapper", which allows:
using(var conn = ...)
{
return conn.Query<FacebookStatusUpdate>("GetPostList"),
commandType: CommandType.StoredProcedure).ToList();
}
(assuming that the column names are a direct match to the property names on FacebookStatusUpdate
)
And for passing parameters:
string region = ...
DateTime minDate = ...
using(var conn = ...)
{
return conn.Query<FacebookStatusUpdate>("GetPostList"),
new { region, minDate },
commandType: CommandType.StoredProcedure).ToList();
}
Upvotes: 1
Reputation: 2524
after executing command.ExecuteReader() you can loop through data with next code (just sample):
var rdr = command.ExecuteReader();
while(rdr.Read())
{
var obj = new MyClass();
obj.Id = (int)rdr["Id"];
if (rdr["Name"] != DBNull.Value)
{
obj.name = (string)rdr["Name"];
}
}
rdr.Close();
this sample reads all fetched data from DB row-by-row.
Also don't forget to read read SqlDataReader manual for more information how to work with readers.
Upvotes: 2
Reputation: 26209
You need to call the reader.Read()
before reading the records.
Example:
String column1="";
String column2="";
while(reader.Read())
{
column1 = reader["column1"].ToString();
column2 = reader["column2"].ToString();
}
Upvotes: 2