SQL Data Reader - handling Null column values

前端 未结 27 2478
甜味超标
甜味超标 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 08:58

    This method is dependent on indexFirstName which should be the zero-based column ordinal.

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

    If you don't know the column index but wan't to check a name you can use this extension method instead:

    public static class DataRecordExtensions
    {
        public static bool HasColumn(this IDataRecord dr, string columnName)
        {
            for (int i=0; i < dr.FieldCount; i++)
            {
                if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
                    return true;
            }
            return false;
        }
    }
    

    And use the method like this:

    if(sqlReader.HasColumn("FirstName"))
    {
      employee.FirstName = sqlreader["FirstName"];
    }
    

提交回复
热议问题