0

我有一个类(实体),如下所示:

Public Class Product

    Property ID As Integer
    Property Name As String
    Property IssueDate As Date
    Property ExpireDate As Date
    Property NextCheckDate As Date

End Class

我正在使用 Entity Framework 5,我想在where子句中使用一些谓词来查询我的数据库。为了为日期创建谓词,我想使用如下函数:

Function GetDateIssuePredicate(fromDate As Date?, toDate As Date?) As Expression(Of Func(Of Product, Boolean))

    Dim predicate As Expressions.Expression(Of Func(Of Product, Boolean))

    If fromDate.hasValue AndAlso toDate.hasValue Then
        predicate = (Function(p) p.IssueDate >= fromDate.Value AndAlso p.IssueDate<= toDate.Value)
    ElseIf fromDate.hasValue Then
        predicate = (Function(p) p.IssueDate >= fromDate.Value)
    ElseIf toDate.hasValue Then
        predicate = (Function(p) p.IssueDate<= toDate.Value)
    End If

    Return predicate

End Function

此函数适用于特定实体字段IssueDate我想避免为不同的实体字段(即ExpireDateNextCheckDate )创建更多执行完全相同的操作的函数。有什么办法可以做到这一点?

4

1 回答 1

0

您可以使它成为 DateTime 的函数,而不是 Product 的函数。

Function GetDateIssuePredicate(fromDate As Date?, toDate As Date?) As Expression(Of Func(Of DateTime, DateTime)) 

    Dim predicate As Expressions.Expression(Of Func(Of DateTime, DateTime)) 

    If fromDate.hasValue AndAlso toDate.hasValue Then 
        predicate = (Function(d) d >= fromDate.Value AndAlso d <= toDate.Value) 
    ElseIf fromDate.hasValue Then 
        predicate = (Function(d) d >= fromDate.Value) 
    ElseIf toDate.hasValue Then 
        predicate = (Function(d) d <= toDate.Value) 
    End If 

    Return predicate 

End Function 
于 2012-10-09T16:42:43.023 回答