SQL Data Reader - handling Null column values

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

    IsDbNull(int) is usually much slower than using methods like GetSqlDateTime and then comparing to DBNull.Value. Try these extension methods for SqlDataReader.

    public static T Def(this SqlDataReader r, int ord)
    {
        var t = r.GetSqlValue(ord);
        if (t == DBNull.Value) return default(T);
        return ((INullable)t).IsNull ? default(T) : (T)t;
    }
    
    public static T? Val(this SqlDataReader r, int ord) where T:struct
    {
        var t = r.GetSqlValue(ord);
        if (t == DBNull.Value) return null;
        return ((INullable)t).IsNull ? (T?)null : (T)t;
    }
    
    public static T Ref(this SqlDataReader r, int ord) where T : class
    {
        var t = r.GetSqlValue(ord);
        if (t == DBNull.Value) return null;
        return ((INullable)t).IsNull ? null : (T)t;
    }
    

    Use them like this:

    var dd = r.Val(ords[4]);
    var ii = r.Def(ords[0]);
    int nn = r.Def(ords[0]);
    

提交回复
热议问题