SQL Data Reader - handling Null column values

前端 未结 27 2190
甜味超标
甜味超标 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:05

    You should use the as operator combined with the ?? operator for default values. Value types will need to be read as nullable and given a default.

    employee.FirstName = sqlreader[indexFirstName] as string;
    employee.Age = sqlreader[indexAge] as int? ?? default(int);
    

    The as operator handles the casting including the check for DBNull.

提交回复
热议问题