0

I want to dynamically select columns from an IQueryable<T> using Linq. T being a ContractDto (in this case).

Currently I have

private static IQueryable<T> Select<T>(IQueryable<T> queryable, IEnumerable<string> columns)
    {
        LambdaExpression lambda = DynamicExpression.ParseLambda(queryable.ElementType, null, $"new ({string.Join(",", columns)})", queryable);

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

However I am getting an error

System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[DynamicClass2]' to type 'System.Linq.IQueryable`1[Business.Dto.ContractDto]'.'

Jamie
  • 380
  • 8
  • 19
  • 1
    possible duplicate: https://stackoverflow.com/questions/16516971/linq-dynamic-select/45205267#45205267 – jazb Dec 10 '18 at 03:07
  • 1
    Possible duplicate of [c# - Dynamically generate linq select with nested properties](https://stackoverflow.com/questions/51753165/c-sharp-dynamically-generate-linq-select-with-nested-properties) – Emre Savcı Dec 10 '18 at 05:39
  • Thanks @JohnB, the code in that answer helped me figure this issue out – Jamie Dec 10 '18 at 20:24

0 Answers0