数据是空的.无法在Null值上调用此方法或属性

sel*_*lvi 15 ado.net

if (!string.IsNullOrEmpty(rd.GetString(2)))
{
    StrBcc = rd.GetString(2);
}
Run Code Online (Sandbox Code Playgroud)

错误:System.Data.SqlTypes.SqlNullValueException:数据为空.无法在Null值上调用此方法或属性.

Ali*_*tad 22

我的解决方案是创建一个扩展方法:

static class DataReaderExtensions
{
    public static string GetStringNullCheck(this IDataReader reader, int ordinal)
    {
        return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我可以用它作为:

 StrBcc = rd.GetStringNullCheck(2);
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望将该类声明为“public”,因为它是一个普遍有用的扩展方法。 (4认同)

Mar*_*rco 11

你应该使用

if (!rd.IsDbNull(2))
    StrBcc = rd.GetString(2);
Run Code Online (Sandbox Code Playgroud)

那是因为当你使用string.IsNullOrEmpty(x)你告诉你的应用程序x是一个字符串时,while是一个数据库空值,它与一个值为null的字符串不同.


cra*_*y_p 5

如果您的值可以为NULL,那么使用SqlTypes可能是一个更安全的解决方案,因为它们都实现了INullable

StrBcc = rd.GetSqlString(2);
Run Code Online (Sandbox Code Playgroud)

或者如果您喜欢扩展方法:

public static class DataReaderExtensions
{
    public static T GetValueOrNull<T>(this SqlDataReader reader, int ordinal) where T : class
    {
        return !reader.IsDBNull(ordinal) ? reader.GetFieldValue<T>(ordinal) : null;
    }

    public static T? GetValueOrNullable<T>(this SqlDataReader reader,  int ordinal) where T : struct 
    {
        if (reader.IsDBNull(ordinal)) return null;
        return reader.GetFieldValue<T>(ordinal);
    }
}
Run Code Online (Sandbox Code Playgroud)