2012-10-09 33 views
0

我有一個類(實體)像下面這樣:創建使用LINQ表達式泛型函數

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 

我使用實體框架5,我想在其中子句使用一些謂詞來查詢我的數據庫。爲了創建一個謂語的日期我想使用的功能如下所示:

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。我想避免爲不同的實體字段創建完全相同的功能(即到期日期,NextCheckDate)。有什麼辦法可以做到這一點?

+0

請參見[動態LINQ](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query- library.aspx) –

+0

謂詞不會返回一個'Boolean'嗎? – Jodrell

+0

因此,成爲一個'表達式(的Func(的DateTime ?,布爾))? – Jodrell

回答

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