現在、動的クエリ生成に式ビルダーを使用しています。
int、date、time、およびstring演算子の動的式を作成しました。今、私はある時点で行き詰まっています。
日時の月の部分を式で比較したい。
datetimeのプロパティを渡していて、そのプロパティの月の式を作成したいと考えています。
コード:
public static Expression GetDynamicquery<TSource>(
string property, object value, ParameterExpression p)
{
var propertyReference = Expression.Property(p, property);
var constantReference = Expression.Constant(value);
var expression = Expression.Equal(propertyReference, constantReference);
MethodInfo method = null;
return Expression.LessThanOrEqual(propertyReference, constantReference);
}
ここでpropertyは、Tsourceに渡すプロパティの名前です。
p
はTsource型のパラメーター式です。
今月の全生年月日のような結果が欲しいです。
質問の答えを得ました。私がしたことは…
コード:
public static Expression GetDynamicquery<TSource>(
string property, object value, ParameterExpression p)
{
var propertyReference = Expression.Property(p, property);
propertyReference = Expression.Property(propertyReference, "Year");
var constantReference = Expression.Constant(value);
return Expression.Equal(propertyReference, constantReference);
}
ここで最初のプロパティ参照は日時式を与えます。
また、その式を使用して、1歩進んで、年のプロパティにアクセスできます。月にできることは同じです。
そのために、Expression.PropertyOrFieldメソッドを使用できます。ただし、エンティティフレームワーククエリで機能するかどうかは不明です。
更新
エンティティフレームワークでは、SqlFunctions.DatePartメソッドを使用できます。
http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions(v=vs.110).aspx
これを式として表すには、Expression.Callが必要です。
http://msdn.microsoft.com/en-us/library/bb349020(v=vs.110).aspx