c# - IQueryable 扩展方法成为表达式

标签 c# expression iqueryable

我正在为现有工具编写一个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/

相关文章:

c# - 从 URL 中删除额外的斜线

c# - COM 与 VB6 和 C# 互操作

c# - Linq To SQL InsertAllOnSubmit 和 DeleteAllOnSubmit

c# - 表达式<Func<T, bool 值>> VS Func<T, bool 值>

c++ - x&&y||z 是如何计算的?

c# - IEnumerable 与 IQueryable 对象 - LinQ to SQL

c# - 如何从代码隐藏动态添加 html 选择控件?

javascript - 如何从 JavaScript 表达式中提取键路径

.net - IQueryable 的 Linq Count() 与 IEnumerable 的 Linq Count()

c# - IQueryable 的顺序是否保留在 C# EF Core 中的实际查询中?