Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to see if a column exists in a data reader [duplicate]

Tags:

c#

idatareader

Is there a way to see if a field exists in an IDataReader-based object w/o just checking for an IndexOutOfRangeException?

In essence, I have a method that takes an IDataReader-based object and creates a strongly-typed list of the records. In 1 instance, one data reader has a field that others do not. I don't really want to rewrite all of the queries that feed this method to include some form of this field if I don't have to. The only way I have been able to figure out how to do it so far is to throw the 1 unique field into a try/catch block as shown below.

try {     tmp.OptionalField = reader["optionalfield"].ToString(); } catch (IndexOutOfRangeException ex) {     //do nothing } 

Is there a cleaner way short of adding the "optional field" to the other queries or copying the loading method so 1 version uses the optional field and the other doesn't?

I'm in the 2.0 framework also.

like image 524
JamesEggers Avatar asked Jul 30 '09 13:07

JamesEggers


1 Answers

I ended up finding a solution using the reader.GetName(int) method. I created the below method to encompass the logic.

public bool ColumnExists(IDataReader reader, string columnName) {     for (int i = 0; i < reader.FieldCount; i++)     {          if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))         {             return true;         }     }      return false; } 
like image 193
JamesEggers Avatar answered Oct 07 '22 01:10

JamesEggers