Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用动态Linq时需要类型为“T”的表达式_C#_Linq_Dynamic Linq - Fatal编程技术网

C# 使用动态Linq时需要类型为“T”的表达式

C# 使用动态Linq时需要类型为“T”的表达式,c#,linq,dynamic-linq,C#,Linq,Dynamic Linq,我正在使用.NETMVC应用程序中的动态Linq库查询SQLServer数据库。到目前为止一切正常 我需要进行动态选择,但始终返回类型为“T”的表达式: 最后我解决了这个问题 public static IQueryable SelectByFields(this IQueryable q, string expression, params object[] values) // IEnumerable<string> fieldNames) { try

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

我需要进行动态选择,但始终返回类型为“T”的表达式:


最后我解决了这个问题

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>;

从外观上看,您需要2个通用参数。从T输入到U输出。否则,唯一可选择的字段将是同一类型容器的字段;类型[]类型=新类型[]{q.ElementType,lambda.Body.Type};返回q.Provider.CreateQueryExpression.CalltypeofQueryable,Select,types,q.Expression,Expression.Quotelambda;'但返回no cast no se puede convertir un objeto de tipo'System.Data.Entity.Infrastructure.DbQuery1[System.Object]'al tipo'System.Linq.IQueryable1[AccesoDatosEF.Sujetos.CLIENTE]'。我认为错误在于表达方式是否应该使用typeofQueryable?请不要在问题中添加答案。我下定决心了。谢谢!!
var aux = context.CLIENTES.SelectByFields("new (ID)") as IQueryable<Object>;