0

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;
    }
ekad
  • 14,436
  • 26
  • 44
  • 46
  • From the looks of this you need 2 generic parameters. From `T` (input) to `U` (output). Else the only fields selectable would be a field that is the same type of container. – leppie Jan 16 '15 at 09:36
  • I probed this 'var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(typeof(T), typeof(object), 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)));' but return no cast **No se puede convertir un objeto de tipo 'System.Data.Entity.Infrastructure.DbQuery`1[System.Object]' al tipo 'System.Linq.IQueryable`1[AccesoDatosEF.Sujetos.CLIENTE]'.** I think the mistake is the expression – Juan Antonio Mañas Jan 16 '15 at 09:49
  • Should you not have `typeof(Queryable)` ? – leppie Jan 16 '15 at 09:53
  • Please don't add the answer in the question. Post an answer instead. – Patrick Hofman Jan 16 '15 at 13:58

1 Answers1

0

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