determine if a field is returned from a datareader
I'm dynamically picking a table to select from and there's one fiel开发者_开发问答d that doesn't exist on all of the tables. Inside my reader, how can I check to see if that field exists in the collection?
I'm using this, but it only determines if it's null...not whether it exists or not:
if (myReader.GetValue(myReader.GetOrdinal("PrePay")) != DBNull.Value)
myModel.PrePay = myReader.GetBoolean(myReader.GetOrdinal("PrePay"));
Have a look at SqlDataReader.GetSchemaTable (assuming myReader is a SqlDataReader).
while(reader.Read())
{
if(reader.GetOrdinal("FieldName")>=0) //field exists
{
....
}
}
for (int i = 0; i < myReader.FieldCount; i++)
{
string name = myReader.GetName(i);
if (string.Equals(name , "PrePay", StringComparison.OrdinalIgnoreCase))
{
object value = myReader.GetValue(i);
if (!Convert.IsDBNull(value))
{
myModel.PrePay = (bool)value;
}
break;
}
}
If your reader returns more than one row then you should perform the lookup just once at the beginning and then cache the ordinal to use when iterating through the resultset.
While(myReader.Read())
{
MessageBox.Show(myReader.Item("PrePay").toString());
}
Basically, if the value of "PrePay" is null, it's doesn't exist otherwise it's exist.
精彩评论