Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a class DataReaderHelper to read column values from DataReader. These methods work fine, but, throw exception for an attempt to read a column value that doesn’t exists in the DataReader.

The DataReaderHelper class methods are like the followings:

public static string GetString(object data)
{
     return ((data == null) || (data == DBNull.Value)) ? string.Empty : data.ToString();
}


I need to know how to handle the problem gracefully, so that, the if the DataReader doesn’t contain the desired column, it doesn't throw any Exception (Rather, returns some default value or so).
Posted

1 solution

when we need to share the same mapping methods for different SQL queries which may have a little differences in their selection list (Which is a very common scenario) and usually we try to do either of the followings:

Include all columns in the selection list of all stored procedures even if not necessary

Or,

Use a try…catch block as follows:

try
{
          string FirstName = DataReaderHelper.GetString(reader["FirstName"]);
}
catch(Exception ex)
{
         //The reader doesn’t have this column in selection
}


Or,

Create different versions of the Mapping methods and create different entities for different queries

Neither of those are not good approaches.

Here is a solution


Add a following private method which does the trick to check the existence of the column value in the DataReader

private static object GetDataForColumn(string columnName, IDataReader reader)
{
     reader.GetSchemaTable().DefaultView.RowFilter = "ColumnName= '" + columnName + "'";
     return reader.GetSchemaTable().DefaultView.Count > 0? reader[columnName]:null; 
}


Basically, it filters the Schema information using the ColumnName as the filter and reads count to determine whether the field exists in the DaraReader.

Now, you can use the method as follows:

public static string GetString(IDataReader reader, string columnName)
{
     object data = GetDataForColumn(columnName, reader);
     return ((data == null) || (data == DBNull.Value)) ? string.Empty : data.ToString();
}


So, you can use the method as follows now:

string FirstName = DataReaderHelper.GetString(reader,"FirstName");


This would handle the situation gracefully :)
 
Share this answer
 
Comments
Dalek Dave 15-Dec-10 3:57am    
Good Answer.
Al-Farooque Shubho 15-Dec-10 4:03am    
Thanks, Dave

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900