2013-06-27 64 views
0

這是我的代碼的片段。使用默認(DateTime)?

var sc = dc.Schedules.FirstOrDefault(s => s.scheduleID == id); 
schedule = new ScheduleModel 
{ 
    ScheduleId = sc.scheduleID, 
    Name = sc.scheduleName, 
    StartDate = sc.startDate.HasValue ? sc.startDate.Value : default(DateTime), 
    EndDate = sc.endDate.HasValue ? sc.endDate.Value : default(DateTime), 
    StatusId = sc.statusID.HasValue ? sc.statusID.Value : default(int), 
    //other properties 
}; 

原代碼沒有檢查sc.startDate.HasValue和ReSharper的抱怨Possible System.InvalidOperationException警告。

然後我添加了這些條件,以便Resharper不再抱怨。但我也想知道在這裏使用default(DateTime) & defualt(int)是否正確。 SQL Server會接受其默認值DateTime的值嗎?或者我應該使用DateTime.Now而不是?

有什麼建議嗎?謝謝。

+0

豈不ReSharper的抱怨nullreference例外,因爲使用數據之前不檢查SC? PS SQL Server不會像默認(DateTime)那樣最小值大約是1753. – Plymouth223

回答

4

DateTime的默認值是1/1/0001 12:00:00 AM而對於SQL Server the DateTime場範圍是January 1, 1753, through December 31, 9999,所以其如果使用NULL,而不是缺省值,因爲你將無法​​存儲 .net框架默認值日期更好SQL Server。

爲了您ScheduleModel類,我會繼續StartDateEndDate作爲DateTime?Nullable<DateTime>

+0

謝謝。這正是我想知道的。那麼你認爲如果忽略了Resharper的警告是安全的嗎? – woodykiddy

+0

是的,那也是我需要檢查的東西。使StartDate和EndDate可爲空也許是更優選的。 – woodykiddy

+1

@woodykiddy,我不確定爲什麼resharper會抱怨它,但是這個特例我想你可以忽略它 – Habib