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
For a string you can simply cast the object version (accessed using the array operator) and wind up with a null string for nulls:
employee.FirstName = (string)sqlreader[indexFirstName];
or
employee.FirstName = sqlreader[indexFirstName] as string;
For integers, if you cast to a nullable int, you can use GetValueOrDefault()
employee.Age = (sqlreader[indexAge] as int?).GetValueOrDefault();
or the null-coalescing operator (??
).
employee.Age = (sqlreader[indexAge] as int?) ?? 0;