I\'m using a SQLdatareader to build POCOs from a database. The code works except when it encounters a null value in the database. For example, if the FirstName column in the
By influencing from getpsyched's answer, I created a generic method which checks column value by its name
public static T SafeGet(this System.Data.SqlClient.SqlDataReader reader, string nameOfColumn)
{
var indexOfColumn = reader.GetOrdinal(nameOfColumn);
return reader.IsDBNull(indexOfColumn) ? default(T) : reader.GetFieldValue(indexOfColumn);
}
Usage:
var myVariable = SafeGet(reader, "NameOfColumn")