我使用SQLdatareader从数据库构建poco。除非在数据库中遇到空值,否则代码可以正常工作。例如,如果数据库中的FirstName列包含空值,则抛出异常。

employee.FirstName = sqlreader.GetString(indexFirstName);

在这种情况下处理空值的最佳方法是什么?


当前回答

我们使用一系列静态方法从数据读取器中提取所有值。创建静态/共享方法的好处是,你不必一遍又一遍地做同样的检查…

静态方法将包含检查空值的代码(参见本页的其他答案)。

其他回答

当在数据读取器中使用列名返回行时,我不认为有NULL列值。

如果你做datareader["columnName"].ToString();它总是会给你一个值,可以是一个空字符串(字符串。如果需要比较,则为空)。

我会使用以下方法,不会太担心:

employee.FirstName = sqlreader["columnNameForFirstName"].ToString();

我想你会想用:

SqlReader.IsDBNull(indexFirstName)

我倾向于用合适的东西替换SELECT语句中的空值。

SELECT ISNULL(firstname, '') FROM people

在这里,我将每个null替换为一个空白字符串。在这种情况下,代码不会抛出错误。

下面是其他人可以根据@marc_s的答案使用的helper类:

public static class SQLDataReaderExtensions
    {
        public static int SafeGetInt(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.IsDBNull(fieldIndex) ? 0 : dataReader.GetInt32(fieldIndex);
        }

        public static int? SafeGetNullableInt(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.GetValue(fieldIndex) as int?;
        }

        public static string SafeGetString(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.IsDBNull(fieldIndex) ? string.Empty : dataReader.GetString(fieldIndex);
        }

        public static DateTime? SafeGetNullableDateTime(this SqlDataReader dataReader, string fieldName)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.GetValue(fieldIndex) as DateTime?;
        }

        public static bool SafeGetBoolean(this SqlDataReader dataReader, string fieldName)
        {
            return SafeGetBoolean(dataReader, fieldName, false);
        }

        public static bool SafeGetBoolean(this SqlDataReader dataReader, string fieldName, bool defaultValue)
        {
            int fieldIndex = dataReader.GetOrdinal(fieldName);
            return dataReader.IsDBNull(fieldIndex) ? defaultValue : dataReader.GetBoolean(fieldIndex);
        }
    }
employee.FirstName = sqlreader[indexFirstName] as string;

对于整数,如果转换为可空整型,则可以使用GetValueOrDefault()

employee.Age = (sqlreader[indexAge] as int?).GetValueOrDefault();

或者空合并操作符(??)。

employee.Age = (sqlreader[indexAge] as int?) ?? 0;