LinqToSql with dates problem
我有一个简单的LinqToSql查询
1 2 3 | from p in GL_PROJECTs where p.CREATE_DT == new DateTime(2009,10,26) select new p |
数据库中的某些记录创建的日期具有非00:00:00的时间部分,因此此查询不会检索该日期。我要实现的是一整天都对时间不敏感的检索。
我尝试了以下操作,并添加了日期,以尝试像这样进行比较:
1 2 3 | from p in GL_PROJECTs where p.CREATE_DT.Date >= new DateTime(2009,10,26) select new p |
但是在LinqPad中,出现以下错误:
'System.Nullable'
does not contain a definition for
'Date' and no extension method 'Date'
accepting a first argument of type
'System.Nullable'
could be found (press F4 to add a
using directive or assembly reference)
有什么想法为什么不起作用以及我可以做些什么来使它起作用?
谢谢
只需检查范围
1 2 3 4 | from p in GL_PROJECTs where p.CREATE_DT >= new DateTime(2009,10,26) && p.CREATE_DT < new DateTime(2009,10,27) select new p |
如果允许CREATE_DT在数据库中具有NULL值,它将被映射为.net中的
您可以通过Nullable类型的Value属性检索其实际日期。
尝试
1 2 3 | from p in GL_PROJECTs where p.CREATE_DT.Value.Date == new DateTime(2009,10,26) select new p |
但是,如果CREATE_DT实际上为null,则将引发异常。为避免此异常,您必须确保Nullable类型确实包含一个值:
1 2 3 | from p in GL_PROJECTs where p.CREATE_DT.HasValue && p.CREATE_DT.Value.Date == new DateTime(2009,10,26) select new p |
如果它可以为空,则需要先使用
1 | p.CREATE_DT.Value.Date |
也就是说,使用