2012-09-07 30 views
4

我想保存時間字段爲空值,如果DateEdit(DEV表示C#Windows應用程序的控制)的EditValue爲空。如何保存空值到MySQL表DateTime字段在C#

如果dateEdit控制有一個編輯值,它保存所選date.If它是空保存默認的日期,但我想保存null值,如果dateEdit值爲null。

示例代碼: 我使用實體框架的工作,

Orders ord= new Orders(); 
ord.OrderDate= dateEdit1.DateTime;**//here i want to save null value if the dateEdit control value is null** 
Objcontext.Orders.AddObject(ord); 
Objcontext.SaveChanges(); 
+0

需要更多信息...你如何將值寫入表格?請張貼一些示例代碼。 – phoog

+0

謝謝你回答我,請告訴我如何空值保存到日期字段 – Vinoth

+0

訂單類的訂購日期屬性應可爲空 - 它應該有類型的日期時間''或'可空'(這是二?不同的寫作方式)。我不太瞭解實體框架,就如何實現這一點向您提供建議。一旦你達到了這個目的,就用'null'關鍵字設置屬性,就像這樣:'ord.OrderDate = null;' – phoog

回答

2

您使用ADO Command with Parameters?如果是這樣,然後嘗試東西此,

// other codes here 
command.AddWithValue("@paramName", (dateEdit.EditValue == null) ? DBNull.Value : dateEdit.EditValue); 

dateEdit Control是DevExpress的成分吧?

,或者嘗試

Orders ord = new Orders(); 
ord.OrderDate = (dateEdit1.DateTime == null ? DBNull.Value : dateEdit1.DateTime); //here i want to save null value if the dateEdit control value is null 
Objcontext.Orders.AddObject(ord); 
Objcontext.SaveChanges(); 

enter image description here

0

您應該設置字段屬性爲NULL接受NULL值。否則,它將保存爲「0000-00-00」。

+0

該字段具有該屬性。 – Vinoth

0

使用空類型:

DateTime ? nullableDate = GetSomeDate(); 

這也適用於其他值類型。

還有DBNull類可能有助於這種操作。使用可能是這樣的:

sqlCommand.Parameters.AddWithValue("created",nullableDate??DBNull.Value); 

或類似的。從.NET Framework 4開始,MS希望我們將空值傳遞給DBNull.Value。

+0

我使用實體框架,請告訴我如何保存空值日期字段 – Vinoth

+0

EF,如果你做的一切權利 – aiodintsov

+0

謝謝aiodintsov現在,我節省了空dateEdit空值會產生可空類型的空列 – Vinoth

0

它可以幫助存儲空日期時間爲您DateEdit。

DateTime? DateEdit = null; 
0
Orders ord = new Orders(); 

if(dateEdit1.EditValue!=null) 

{ord.OrderDate = dateEdit1.DateTime.Date} 

else 

{ord.OrderDate= null} 

dateEdit control value is null 
Objcontext.Orders.AddObject(ord); 
Objcontext.SaveChanges(); 

現在,我能夠保存在DateEditDateTimenull值。

相關問題