使用默认值(DateTime)
本文关键字:DateTime 默认值 | 更新日期: 2023-09-27 18:20:00
这是我的代码片段。
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
吗?
有什么建议吗?谢谢
DateTime
的默认值是1/1/0001 12:00:00 AM
,而对于SQL Server,DateTime字段范围是January 1, 1753, through December 31, 9999
,因此如果使用NULL
而不是默认值会更好,因为将无法在SQL Server中存储日期的.Net框架默认值。
对于您的类ScheduleModel
,我会将StartDate
和EndDate
保留为DateTime?
或Nullable<DateTime>