我有一个类(实体),如下所示:
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 。我想避免为不同的实体字段创建更多功能完全相同的功能(即 ExpireDate , NextCheckDate )。有没有办法实现这个目标?
答案 0 :(得分: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