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 

posted @ 2016-05-24 16:55  ®Geovin Du Dream Park™  阅读(398)  评论(0编辑  收藏  举报