我正在为现有工具编写一个IQueryable
实现。该工具最常见的功能之一是类似于数据库中存在的查询。为了支持这一点,我想使用如下方法扩展 IQueryable
:
public static IQueryable<T> WhereExists<T, U>(
this IQueryable<T> Current,
IQueryable<U> Other,
Func<T, Field> CurrentSelector) where U : Entity
{
return WhereExists(Current, Other, x => x.ID, CurrentSelector);
}
public static IQueryable<T> WhereExists<T, U>(
this IQueryable<T> Current,
IQueryable<U> Other,
Func<U, Field> RemoteSelector,
Func<T, Field> CurrentSelector) where U : Entity
{
throw new NotImplementedException(
"This method is only implemented for db-backed queries.");
}
扩展方法的存在使我能够通过编译器,真正的功能将在表达式访问者中。
问题是我希望它显示在表达式中,但它一直运行到扩展方法。是否必须遵循一些限制才能将其放入表达式中(例如使用 .Where 等)?
最佳答案
让我们看看 .NET 框架是如何做到这一点的:
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
return source.Provider.CreateQuery<TSource>(
Expression.Call(null, ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(TSource) }), new Expression[] { source.Expression, Expression.Quote(predicate) }));
}
它们将参数打包到调用表达式中。
我建议您尽可能坚持使用默认的 Queryable
方法,这样您就不必执行太多此技巧。
关于c# - IQueryable 扩展方法成为表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24119746/