我有以下實例:如何修改表達式<Func <???, bool>>的類型參數?
Expression<Func<IRequiredDate, bool>>
我想將其轉換爲以下的實例,因此它可以用於運行在實體框架查詢:
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泛型類型參數嗎? –
我已經將示例代碼添加到問題中,參見上文。 –