SQL Data Reader - handling Null column values

前端 未结 27 2227
甜味超标
甜味超标 2020-11-22 08:53

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

27条回答
  •  悲哀的现实
    2020-11-22 09:25

    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;
    

提交回复
热议问题