我正在使用PredicateBuilder生成动态搜索子句。在下面的示例代码中,有没有一种方法可以修改SetDateTimePredicate
,以便将其用于任何DateTime
属性SomeType
?
Expression<Func<SomeType, bool>> somePredicate = null;
somePredicate = somePredicate.Or(
SetDateTimePredicate(comparisonOperator, dateTime1, dateTime2));
private Expression<Func<SomeType, bool>> SetDateTimePredicate(
Enums.ComparisonOperator comparison,
DateTime dateTime1,
DateTime dateTime2)
{
switch (comparison)
{
case Enums.ComparisonOperator.IsLessThan:
return p => p.SomeDateProperty < dateTime1;
case Enums.ComparisonOperator.IsLessThanOrEqualTo:
return p => p.SomeDateProperty <= dateTime1;
case Enums.ComparisonOperator.IsGreaterThan:
return p => p.SomeDateProperty > dateTime1;
case Enums.ComparisonOperator.IsGreaterThanOrEqualTo:
return p => p.SomeDateProperty >= dateTime1;
case Enums.ComparisonOperator.IsBetween:
return p => p.SomeDateProperty >= dateTime1
&& p.SomeDateProperty <= dateTime2;
default:
return p => p.SomeDateProperty == dateTime1;
}
}
我尝试了一种扩展方法,但得到了这个错误:
System.NotSupportedException occurred
Message="Method 'Boolean Compare(System.DateTime, ComparisonOperator, System.DateTime, System.DateTime)' has no supported translation to SQL."
扩展方法:
public static bool Compare(
this DateTime dateToCompare,
Enums.ComparisonOperator comparison,
DateTime dateTime1,
DateTime dateTime2)
{
switch (comparison)
{
case Enums.ComparisonOperator.IsLessThan:
return dateToCompare < dateTime1;
case Enums.ComparisonOperator.IsLessThanOrEqualTo:
return dateToCompare <= dateTime1;
case Enums.ComparisonOperator.IsGreaterThan:
return dateToCompare > dateTime1;
case Enums.ComparisonOperator.IsGreaterThanOrEqualTo:
return dateToCompare >= dateTime1;
case Enums.ComparisonOperator.IsBetween:
return dateToCompare >= dateTime1
&& dateToCompare <= dateTime2;
default:
return dateToCompare == dateTime1;
}
}
带有扩展方法的示例:
somePredicate = somePredicate.Or(
p => p.SomeDateProperty.Compare(comparisonOperator, dateTime1, dateTime2));