SQL Data Reader - handling Null column values

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

    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")
    

提交回复
热议问题