SQL Data Reader - handling Null column values

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

    You can write a Generic function to check Null and include default value when it is NULL. Call this when reading Datareader

    public T CheckNull(object obj)
            {
                return (obj == DBNull.Value ? default(T) : (T)obj);
            }
    

    When reading the Datareader use

                            while (dr.Read())
                            {
                                tblBPN_InTrRecon Bpn = new tblBPN_InTrRecon();
                                Bpn.BPN_Date = CheckNull(dr["BPN_Date"]);
                                Bpn.Cust_Backorder_Qty = CheckNull(dr["Cust_Backorder_Qty"]);
                                Bpn.Cust_Min = CheckNull(dr["Cust_Min"]);
                             }
    

提交回复
热议问题