Can't find OrderBy on Queryable with the “supplied arguments”.

前端 未结 1 1980
星月不相逢
星月不相逢 2021-02-08 23:43

I have a method that I want to use to sort a list:

private static IQueryable BuildQuery(IQueryable query, 
                                    


        
1条回答
  •  鱼传尺愫
    2021-02-09 00:32

    Since you want your property selector expression to make the appropriate calls dynamically, you must create a new expression for it. You cannot use the provided selector as-is since it is currently typed Expression> and not returning your specific type Expression>. You might be able to get it to compile by changing the type arguments of the call to accept object but it will not work as expected since it will be doing object reference comparisons (and your LINQ provider will may reject it anyway).

    To recreate your selector expression, you could do this:

    private static IQueryable BuildQuery(
        IQueryable query,
        string methodName,
        Expression> property)
    {
        var typeArgs = new[] { query.ElementType, property.Body.Type };
        var delegateType = typeof(Func<,>).MakeGenericType(typeArgs);
        var typedProperty = Expression.Lambda(delegateType, property.Body, property.Parameters);
    
        var methodCall = Expression.Call(
            typeof(Queryable),
            methodName,
            typeArgs,
            query.Expression,
            typedProperty);
    
        return query.Provider.CreateQuery(methodCall);
    }
    

    A nice alternative to doing this would be to make the property type generic too. That way, you'll get an appropriately strongly typed selector from the start.

    private static IQueryable BuildQuery(
        IQueryable query,
        string methodName,
        Expression> property)
    {
        var typeArguments = property.Type.GetGenericArguments();
    
        var methodCall = Expression.Call(
            typeof(Queryable),
            methodName,
            typeArguments,
            query.Expression,
            property);
    
        return query.Provider.CreateQuery(methodCall);
    }
    

    0 讨论(0)
提交回复
热议问题