I need to determine the structure of a result set returned by ExecuteReader. I am using the following approach:
public List<NameAndType> ResultSetStructure(DataTable columns)
{
var ret = new List<NameAndType>();
foreach (DataRow column in columns.Rows)
{
ret.Add(new NameAndType { Name = column[NameIndex].ToString(),
Type = column[TypeIndex].ToString()
});
}
return ret;
}
(snip)
using (SqlDataReader dr = command.ExecuteReader())
{
var rawColumns = dr.GetSchemaTable();
var columns = ResultSetStructure(rawColumns);
This gives me column names and types, but I would also like to know if the column is nullable, so that I know which of the following options to choose:
decimal density = dr.GetDecimal(0);
decimal? density = dr.IsDBNull(0) ? (decimal?)null : dr.GetDecimal(0);
Can I accomplish that? TIA.
Edit: I just found what I need:
开发者_JS百科column[13].ToString()
I guess there is no such way to know whether a column is nullable or not. You can try writing an extension method something like below:
public static decimal GetDecimal(this SqlDataReader reader, int columnIndex)
{
if(!reader.IsDBNull(columnIndex))
{
return reader.GetDecimal(colIndex);
}
else
{
return 0;
}
}
Hope this would be some help!!
The following code gets the job done:
ret.Add(new NameAndType { Name = column[NameIndex].ToString(),
Type = column[TypeIndex].ToString(),
IsNullable = column[13].ToString().Equals("True")
精彩评论