I have faced some interesting situation. I have the following code to populate value of field from DB (ASP.net):
SqlConnection connect =
new SqlConnection(
@"conn-string");
SqlCommand toDo = new SqlCommand(InfoQuery, connect);
toDo.CommandTimeout = 6000;
connect.Open();
using (SqlDataReader reader = toDo.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
///......retrieving some fields in the same way as below
foo = reader.SafeGetString(7);
int temp = reader.SafeGetInt32(8);
///......retrieving again
}
}
connect.close()
The connection is established, all params are correct. In SQL Server Management Studio the query associated with toDo command works just perfect. In program when running every field to the temp value (not including temp) is retrieved and set. But when reading temp value, i get the following exception:
Invalid attempt to read when no data is present.
And here are my extension methods:
public static class ExtentionMethods
{
public static string SafeGetString(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
return "NULL VALUE";
}
public static int SafeGetInt32(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
return reader.GetInt32(colIndex);
return -1;
}
public static DateTime SafeGetDateTime(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
{
try
{
}
catch
{
return new DateTime(1800, 1, 1);
}
}
return new DateTime(1800, 1, 1);
}
}
Query:
SELECT TOP 1000 [ID0]
,[Id1]
,[Id2]
,Id1+Id2+'0' AS BC
,[Id3]
,[Id4]
,[Id5]
,CAST([Date] AS nvarchar(max))
,[int]
,[Id7]
,[Id8]
,IsNull(foo,'dsf')+' '+IsNull(bar,'dsf')+', '
+IsNull(fgm,'fggf')+', fgfggf '+IsNull(gfgf,'gfgf')+
','+dfsdfsdsf+', '+dsffddf AS dsadsa
,[fg]
,[fds]
FROM tbl
inner join tbl1 on tbl1.ID=ID1
inner join tbl2 on tbl2.ID=ID2
WHERE Id4=12
What the problem could be?
I don’t think you need all this extensions methods, and you should access columns by name :
int?orDateTime?will allow nulls and??will affect a default value if the column is null.