私は、次のインスタンスを持っている:Expression <Func <???, bool>>の型パラメータを変更する方法は?
Expression<Func<IRequiredDate, bool>>
Entity Frameworkの中でクエリを実行するために使用することができますので、私は、次のインスタンスに変換したい:
Expression<Func<TModel, bool>>
この例えば、私はIRequiredDateを実装する任意のモデルに一般的なフィルタリング・クエリーを活用できるようになります。:
// In some repository function:
var query = DbContext.Set<Order>()
.FilterByDateRange(DateTime.Today, DateTime.Today);
var query = DbContext.Set<Note>()
.FilterByDateRange(DateTime.Today, DateTime.Today);
var query = DbContext.Set<Complaint>()
.FilterByDateRange(DateTime.Today, DateTime.Today);
// The general purpose function, can filter for any model implementing IRequiredDate
public static IQueryable<TModel> FilterByDate<TModel>(IQueryable<TModel> query, DateTime startDate, DateTime endDate) where TModel : IRequiredDate
{
// This will NOT WORK, as E/F won't accept an expression of type IRequiredDate, even though TModel implements IRequiredDate
// Expression<Func<IRequiredDate, bool>> dateRangeFilter = x => x.Date >= startDate && x.Date <= endDate;
// query = query.Where(dateRangeFilter);
// This also WON'T WORK, x.Date is compiled into the expression as a member of IRequiredDate instead of TModel, so E/F knocks it back for the same reason:
// Expression<Func<TModel, bool>> dateRangeFilter = x => x.Date >= startDate && x.Date <= endDate;
// query = query.Where(dateRangeFilter);
// All you need is lov.... uh... something like this:
Expression<Func<IRequiredDate, bool>> dateRangeFilter = x => x.Date >= startDate && x.Date <= endDate;
Expression<Func<TModel, bool>> dateRangeFilterForType = ConvertExpressionType<IRequiredDate, TModel>(dateRangeFilter); // Must convert the expression from one type to another
query = query.Where(dateRangeFilterForType) // Ahhhh. this will work.
return query;
}
public static ConvertExpressionType<TInterface, TModel>(Expression<Func<TInterface, bool>> expression)
where TModel : TInterface // It must implement the interface, since we're about to translate them
{
Expression<Func<TModel, bool>> newExpression = null;
// TODO: How to convert the contents of expression into newExpression, modifying the
// generic type parameter along the way??
return newExpression;
}
私は、彼らはさまざまな種類であり、できないことを理解キャストする。しかし、新しいExpression<Func<TModel, bool>>
を作成し、提供されたExpression<Func<IRequiredDate, bool>>
の内容に基づいてそれを再構築する方法があるかどうか疑問に思っています。どのタイプの参照もIRequiredDate
からTModel
に切り替えています。
これはできますか?
質問の理解に問題があります。あなたは具体的な例を挙げることができますか? – Dai
TModelジェネリック型パラメータですか? –
上記のサンプルコードを質問に追加しました。 –