DataBase datetime null句柄

时间:2013-04-11 08:54:34

标签: c# asp.net .net sql database

我有以下代码:

var distinctRows = 
      (from row in ds.GetTable(this.TagShortName).AsEnumerable()
         select new Audit    
          {
             ID =row.Field<long>("ID"),
             UpdatedBy =string.Format("{0} {1}", 
                                      row.Field<string>("UpdatedByFirstName"),
                                      row.Field<string>("UpdatedByLastName")),
             UpdatedOn = ow.Field<DateTime>("UpdatedOn")
          }).Distinct(new AuditComparer());

当我在UpdateOn字段中有空值时,它会抛出异常:

UpdatedOn =row.Field<DateTime>("UpdatedOn")

exception:无法将DBNull.Value强制转换为'System.DateTime'。请使用可空类型。

如何处理?

2 个答案:

答案 0 :(得分:1)

UpdatedOn可以为空或

UpdatedOn = row.Field<DateTime?>("UpdatedOn")?? DateTime.MinValue

答案 1 :(得分:0)

使用Nullable<DateTime>DateTime?

UpdatedOn = row.Field<DateTime?>("UpdatedOn")