SQL Data Reader - handling Null column values

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

    how to about creating helper methods

    For String

    private static string MyStringConverter(object o)
        {
            if (o == DBNull.Value || o == null)
                return "";
    
            return o.ToString();
        }
    

    Usage

    MyStringConverter(read["indexStringValue"])
    

    For Int

     private static int MyIntonverter(object o)
        {
            if (o == DBNull.Value || o == null)
                return 0;
    
            return Convert.ToInt32(o);
        }
    

    Usage

    MyIntonverter(read["indexIntValue"])
    

    For Date

    private static DateTime? MyDateConverter(object o)
        {
            return (o == DBNull.Value || o == null) ? (DateTime?)null : Convert.ToDateTime(o);
        }
    

    Usage

    MyDateConverter(read["indexDateValue"])
    

    Note: for DateTime declare varialbe as

    DateTime? variable;
    

提交回复
热议问题