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 database contains a null value, an exception is thrown.
employee.FirstName = sqlreader.GetString(indexFirstName);
How can I handle null values in this situation?
You need to check for
IsDBNull:That’s your only reliable way to detect and handle this situation.
I wrapped those things into extension methods and tend to return a default value if the column is indeed
null:Now you can call it like this:
and you’ll never have to worry about an exception or a
nullvalue again.