c# - Expression.Call 跳过或接听

标签 c# .net entity-framework linq .net-core

我制作了通用功能,它在运行时从 JSON 过滤器 编译为 Expression 并且在我的 IQueryable 上进行 Skip 和 Take 调用时出现问题,以便完整编译(没有 exec sp_executesql)在 SQL 中

我的方法:

public static class PagingExtensions
{
    public static IQueryable<T> Page<T>(this IQueryable<T> query, QueryRequest queryRequest) where T : class
    {
        //if (queryRequest.Skip.HasValue)
        //{
          //query = query.Skip(queryRequest.Skip.Value);
        //}

        //if (queryRequest.Take.HasValue)
          //{
            //query = query.Take(queryRequest.Take.Value);
        //}
        var methodName = "Skip";
        var resultExp = Expression.Call(
            typeof(IQueryable),
            "Skip",
            Type.EmptyTypes,
            Expression.Constant(queryRequest.Skip.Value));

        query = query.Provider.CreateQuery<T>(resultExp);


        return query;
    }
}

异常(exception):

InvalidOperationException: No method 'Skip' on type 'System.Linq.IQueryable' is compatible with the supplied arguments.

最佳答案

Skip方法不是IQueryable的实例方法,而是静态Queryable类的扩展。

您需要获取通用方法信息并将源查询作为第一个参数传递:

MethodInfo method = typeof(Queryable).GetMethod("Skip").MakeGenericMethod(typeof(T));
var resultExp = Expression.Call(
                       method,
                       query.Expression, 
                       Expression.Constant(queryRequest.Skip.Value));

关于c# - Expression.Call 跳过或接听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55257967/

相关文章:

c# - 使 .NET TextBox 工作 FIFO 风格

c# - 如何在C#中记录Leap Motion的帧以进行手震跟踪?

c# - 单个 View 上文件类型的多个输入字段

c# - 如何在 Pi 的 C# 程序中将小数点精确到 n 位

c# - 对普通类进行单元测试覆盖是好习惯吗

.net - .ocx 文件和 .Net 控件之间的区别

c# - Linq表达式(curry参数)传递给linq to entities

c# - 将 Entity Framework .Take() 操作转移到查询结束

c# - ADO.NET Entity Framework ObjectContext - 缓存问题

c# - 过程或函数需要未提供的参数