Juan Antonio Mañas Juan Antonio Mañas - 2 months ago 47
C# Question

Expression of type 'T' expected when using Dynamic Linq

I'm using the Dynamic Linq Library in my .NET MVC application to query a SQL Server database. It's all working fine so far.

I need to make a dynamic select but always return Expression of type 'T' expected:

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

Answer

Finally I solve the problem

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

And call to method

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