我在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)'!StartDate.HasValue',或者2)只需'StartDate == null' – Ray 2012-02-01 16:19:41