SQL Data Reader - handling Null column values

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

    You may use the conditional operator:

    employee.FirstName = sqlreader["indexFirstName"] != DBNull.Value ? sqlreader[indexFirstName].ToString() : "";
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:06

    I am using the code listed below to handle null cells in an Excel sheet that is read in to a datatable.

    if (!reader.IsDBNull(2))
    {
       row["Oracle"] = (string)reader[2];
    }
    
    0 讨论(0)
  • 2020-11-22 09:08

    you can ever check for this as well

    if(null !=x && x.HasRows)
    { ....}
    
    0 讨论(0)
  • 2020-11-22 09:09

    I don't think there's a NULL column value, when rows are returned within a datareader using the column name.

    If you do datareader["columnName"].ToString(); it will always give you a value that can be a empty string (String.Empty if you need to compare).

    I would use the following and wouldn't worry too much:

    employee.FirstName = sqlreader["columnNameForFirstName"].ToString();
    
    0 讨论(0)
  • 2020-11-22 09:09

    I think you would want to use:

    SqlReader.IsDBNull(indexFirstName)
    
    0 讨论(0)
提交回复
热议问题