0

我们Nullable object must have a value今天在这行代码上遇到了一个错误:

list = From x In Me Where x.FooDate.HasValue AndAlso x.FooDate.Value.Date >= barDate

有趣的是,我确信这曾经可以正常工作(并且基础数据中总是有少量空值)。从逻辑上讲,它对我来说看起来不错。检查HasValueAndAlso 看起来好像他们将保护我们免受任何 Null 危险。

但似乎突然间他们不是了。我错过了什么吗?

好的,我们可以将其更正为这样,从而消除了错误:

list = From x In Me Where If(x.FooDate.HasValue, x.FooDate.Value.Date >= barDate,False)

但这在我看来不太可读。有什么想法吗?

更新...和忏悔
在简化上面的代码以缩短行时,我遗漏了代码的关键部分。最初的问题应该是这样的:

list = From x In Me Where x.FooDate.HasValue AndAlso x.FooDate.Value.Date >= fromDate And x.FooDate.Value.Date <= toDate

由于短路和运算符优先级的规则(如我自己很久以前的问题的答案中所述),我需要在指令的第二部分周围添加括号,以停止 LINQ 评估第二部分x.FooDate.Value.Date

list = From x In Me Where x.FooDate.HasValue AndAlso (x.FooDate.Value.Date >= fromDate and x.FooDate.Value.Date <= toDate)

感谢这两个答案都提供了快速测试代码来验证 LINQ 确实遵守 AndAlso 并迫使我更仔细地研究原始问题。

4

2 回答 2

1

我很确定您的查询是安全的,至少以下示例代码是:

Dim dateList As New List(Of Nullable(Of Date))
For i As Int32 = 0 To 12
    If (i Mod 3 = 0) Then
        dateList.Add(Nothing)
    Else
        dateList.Add(New Date(2012, i, 1))
    End If
Next
Dim july = New Date(2012, 7, 1)
Dim fromJuly = (From m In dateList
      Where m.HasValue AndAlso m.Value.Date >= july).ToList

注意:如果我替换AndAlsoAnd我会得到你的例外。

所以问题一定出在其他地方。请向我们展示更多您的课程。

于 2012-01-05T17:49:42.477 回答
1

它应该工作。我编写了这段代码,它对我来说很好,即使barDate设置为Nothing.

Sub Main()

    Dim barDate As Nullable(Of DateTime) = Nothing

    Dim List = From x In GetDates() Where x.FooDate.HasValue AndAlso x.FooDate.Value.Date > barDate

    Console.WriteLine(List.Count())

End Sub

Function GetDates() As List(Of Foo)
    Dim l = New List(Of Foo)
    l.Add(New Foo With {.FooDate = DateTime.Now})
    l.Add(New Foo)
    Return l
End Function

Class Foo
    Private m_fooDate As DateTime?
    Public Property FooDate() As DateTime?
        Get
            Return m_fooDate
        End Get
        Set(ByVal value As DateTime?)
            m_fooDate = value
        End Set
    End Property

End Class
于 2012-01-05T18:02:28.337 回答