当datetime可能为null时,Linq子句

时间:2014-08-22 09:04:39

标签: vb.net linq datetime dbnull

我还在DataTable中复制了一个SQL表,以通过以下结构提高性能:

*id_configuration* integer <br>
*id_customer* integer <br>
*id_location* integer   <br>
*validfrom* datetime     <br>
*validuntil* datetime   **ALLOW NULL** <br>
*deviceid*  integer  <br>
*deviceport* integer     <br>

当配置发生变化时,我正在插入另一条记录,其中包含validfrom =开始日期并且有效直到= NULL并且我正在用valituntil = startdate.addseconds(-1)更新上一条记录

我需要为特定日期找到“id_customer”,即使配置处于活动状态(validuntil = NULL),如:

SELECT id_customer 
FROM MyTable 
WHERE
    id_location = 11 
    AND deviceid = 122 
    AND deviceport = 3 
    AND validfrom > '2014-08-22 10:30:00' 
    AND (validuntil < '2014-08-22 10:30:00' or validuntil is NULL) 

我正在尝试使用以下LINQ查询查询DataTable

Dim cfg = From u In MyDataTable 
    Where (u("id_location") = 11 And_ 
    u("deviceid") = 122 And_ 
    u("deviceport") = 3 And_ 
    u("validfrom") > '2014-08-22 10:30:00' And_ 
    ((u.Field(Of Nullable(Of DateTime))("validuntil") Is Nothing) Or u("validuntil") < '2014-08-22 10:30:00') 
    Select u("id_customer") 

但我收到以下错误:

  

运营商'&gt;'未定义类型“DBNull”并键入“Date”。

1 个答案:

答案 0 :(得分:1)

使用Not nullable.HasValue代替,您还应始终使用AndAlsoOrElse代替AndOr。通过Let

使用变量也更具可读性和效率
Dim cfg = From u In MyDataTable 
          Let validuntil = u.Field(Of DateTime?)("validuntil")
          Where ... AndAlso _
          (Not validuntil.HasValue OrElse validuntil.Value < New Date(2014,08,22))
          Select u.Fiueld(Of Int32)("id_customer") 

What is the difference between And and AndAlso in VB.NET?