处理DateTime DBNull
我已经在SO上看过很多很多这样的版本,但是它们似乎都不能满足我的需求。
我的数据来自供应商数据库,该数据库允许DateTime字段为null。 首先,我将数据拉入DataTable。
using (SqlCommand cmd = new SqlCommand(sb.ToString(), conn)) using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(dt); }
我正在将DataTable转换为List 进行处理。
var equipment = from i in dt.AsEnumerable() select new Equipment() { Id = i.Field("ID"), BeginDate = i.Field("BeginDate"), EndDate = i.Field("EndDate"), EstimatedLife = i.Field("EstimatedLife") }
那么,在这个实例中如何检查DBNull? 我试着写一个方法。
public DateTime CheckDBNull(object dateTime) { if (dateTime == DBNull.Value) return DateTime.MinValue; else return (DateTime)dateTime; }
一种可能的选择是使用语法DateTime?
将其存储为可以为空的日期时间DateTime?
以下是MSDN关于使用可空类型的链接
使用IsDBNull()
System.Convert.IsDBNull(value);
或者如果你有一个SqlDataReader
reader.IsDBNull(ordinal);
并使您的DateTime
属性可以为空( DateTime?
)并在DBNull
情况下设置为null
。 Field
将自动执行此操作。
我发现处理此问题的最简单方法是使用“as”关键字将字段强制转换为数据类型。 这适用于可以为null的数据库字段,并且非常简单。
这里有更多细节: 直接投射与’as’运算符?
例:
IDataRecord record = FromSomeSqlQuerySource; string nullableString; DateTime? nullableDateTime; nullableString = record["StringFromRecord"] as string; nullableDateTime = record["DateTimeFromRecord"] as DateTime?;
这是我用来读取日期时间的一些代码示例
我确定它可以写得更好,但对我来说运行正常
public DateTime? ReadNullableDateTimefromReader(string field, IDataRecord data) { var a = data[field]; if (a != DBNull.Value) { return Convert.ToDateTime(a); } return null; } 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; }
您应该使用DataRow["ColumnName"] is DBNull
来比较DateTime null。
例如:
if(studentDataRow["JoinDate"] is DBNull) { // Do something here }