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));