csharp: DBNull and DateTime
/// <summary> /// /// </summary> /// <param name="dateTime"></param> /// <returns></returns> public DateTime CheckDBNull(object dateTime) { if (dateTime == DBNull.Value) return DateTime.MinValue; else return (DateTime)dateTime; } /// <summary> /// /// </summary> /// <param name="field"></param> /// <param name="data"></param> /// <returns></returns> public DateTime? ReadNullableDateTimefromReader(string field, IDataRecord data) { var a = data[field]; if (a != DBNull.Value) { return Convert.ToDateTime(a); } return null; } /// <summary> /// /// </summary> /// <param name="field"></param> /// <param name="data"></param> /// <returns></returns> public DateTime ReadDateTimefromReader(string field, IDataRecord data) { DateTime value; var valueAsString = data[field].ToString(); try { value = DateTime.Parse(valueAsString); } catch (Exception) { throw new Exception("Cannot read Datetime from reader"); } return value; } }
menu.IsMainMenu = (!DBNull.Equals(reader["IsMainMenu"], null)) ? (bool)reader["IsMainMenu"] : true; menu.Remark = (!DBNull.Equals(reader["Remark"], null)) ? (string)reader["Remark"].ToString() : ""; menu.ParentMenuId = (!DBNull.Equals(reader["ParentMenuId"], null)) ? (int)reader["ParentMenuId"] : 0; menu.TreeLevel = (!DBNull.Equals(reader["TreeLevel"], null)) ? (int)reader["TreeLevel"] : 0; menu.SortIndex = (!DBNull.Equals(reader["SortIndex"], null)) ? (int)reader["SortIndex"] : 0; menu.CreatedOn = CheckDBNull(reader["CreatedOn"]);// (!object.Equals(reader["CreatedOn"], null)) ? (DateTime)reader["CreatedOn"] : DateTime.Now;
https://github.com/mathnet
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)