2012-02-01 30 views
11

我在C#中有一個可以爲空的datetime對象。Nulllable DateTime和數據庫

DateTime? StartDate = new DateTime(); 

然後我檢查用戶提交的值,以確定是否一個日期是適用於本記錄:

if (Complete == "N/A") 
{ 
    StartDate = null; 
} 

現在我來我的查詢可能會或可能不會被插入零日期時間:

using (SqlCommand command = new SqlCommand(updateSql, db)) 
{ 
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = StartDate; 
} 

正如你可能預期,如果開始日期爲空,那麼我得到一個錯誤,類型不正確。從這裏出發的最佳方式是什麼?

我已經考慮檢查startdate爲空,但我不知道如何做到這一點時,類型可爲空。

+1

順便說一句,你可以很容易地檢查是否可空類型有兩種方式無效。 1)'!StartDate.HasValue',或者2)只需'StartDate == null' – Ray 2012-02-01 16:19:41

回答

18

這將傳遞一個數據庫NULL值作爲參數,如果起始日期爲null:

using (SqlCommand command = new SqlCommand(updateSql, db)) 
{ 
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = (object)StartDate ?? DBNull.Value; 
} 
+0

這就是我正在嘗試的,不知道這個簡寫語法! :) – deed02392 2012-02-01 16:16:43

+0

錯誤也是這樣:運營商'??'不能應用於system.datetime類型的操作數?和system.dbnull。 – deed02392 2012-02-01 16:20:36

+0

@ deed02392用簡單的物體固定到物體上 – 2012-02-01 16:22:51

1
using (SqlCommand command = new SqlCommand(updateSql, db)) 
{ 
    if (StartDate.HasValue()) 
     command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value 
      = StartDate; 
    else 
     command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value 
      = DBNull.Value; 
} 
相關問題