SQL Data Reader - handling Null column values

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

    You need to check for IsDBNull:

    if(!SqlReader.IsDBNull(indexFirstName))
    {
      employee.FirstName = sqlreader.GetString(indexFirstName);
    }
    

    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:

    public static string SafeGetString(this SqlDataReader reader, int colIndex)
    {
       if(!reader.IsDBNull(colIndex))
           return reader.GetString(colIndex);
       return string.Empty;
    }
    

    Now you can call it like this:

    employee.FirstName = SqlReader.SafeGetString(indexFirstName);
    

    and you'll never have to worry about an exception or a null value again.

提交回复
热议问题