0

这是我的代码片段。

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改用?

有什么建议么?谢谢。

4

1 回答 1

4

的默认值DateTime1/1/0001 12:00:00 AM,而对于SQL Server,DateTime字段范围是January 1, 1753, through December 31, 9999,因此如果您使用NULL而不是默认值会更好,因为您将无法在 SQL Server 中存储日期的 .Net 框架默认值。

对于你的课ScheduleModel,我会保留StartDateand EndDateas DateTime?orNullable<DateTime>

于 2013-06-27T03:18:26.367 回答