【问题标题】:Expression of type 'T' expected when using Dynamic Linq使用 Dynamic Linq 时预期的“T”类型表达式
【发布时间】:2015-03-14 20:58:07
【问题描述】:

我在我的 .NET MVC 应用程序中使用动态 Linq 库来查询 SQL Server 数据库。到目前为止一切正常。

我需要进行动态选择,但总是返回预期的“T”类型表达式

public static IQueryable<T> SelectByFields<T>(this IQueryable<T> q, string expression, params object[] values) // IEnumerable<string> fieldNames)
{
    try
    {
        var param = Expression.Parameter(typeof(T), "p");
        var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(new ParameterExpression[] { param }, typeof(T), expression, values);

        Type[] types = new Type[] { q.ElementType, lambda.Body.Type };
        return q.Provider.CreateQuery<T>(Expression.Call(typeof(Queryable), "Select", types, q.Expression, Expression.Quote(lambda)));
    }
    catch
    {
        return q;
    }

【问题讨论】:

  • 从这个看起来你需要2个通用参数。从T(输入)到U(输出)。否则,唯一可选择的字段将是与容器类型相同的字段。
  • 我探索了这个 'var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(typeof(T), typeof(object), expression, values); Type[] 类型 = new Type[] { q.ElementType, lambda.Body.Type }; return q.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Select", types, q.Expression, Expression.Quote(lambda)));'但不返回任何演员 No se puede convertir un objeto de Tipo 'System.Data.Entity.Infrastructure.DbQuery1[System.Object]' al tipo 'System.Linq.IQueryable1[AccesoDatosEF.Sujetos.CLIENTE]'。 我认为错误是表达式
  • 不应该有typeof(Queryable&lt;T&gt;)吗?
  • 请不要在问题中添加答案。而是发布答案。
  • 我解决了。非常感谢!!

标签: c# linq dynamic-linq


【解决方案1】:

我终于解决了问题

public static IQueryable SelectByFields(this IQueryable q, string expression, params object[] values) // IEnumerable<string> fieldNames)
    {
        try
        {
            if (q == null)
                throw new ArgumentNullException("source");

            if (expression == null) 
                throw new ArgumentNullException("selector");

            LambdaExpression lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(q.ElementType, null, expression, values);
            Type[] types = new Type[] { q.ElementType, lambda.Body.Type };

            return q.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Select", types, q.Expression, Expression.Quote(lambda)));
        }
        catch
        {
            return q;
        }
    }

并调用方法

var aux = context.CLIENTES.SelectByFields("new (ID)") as IQueryable<Object>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2018-10-27
    相关资源
    最近更新 更多