EF 6 Core IEnumerable<T> Projection to Dynamic Object

195 Views Asked by At

I have been struggling on this for a day now and I can't figure out how to do this:

I have an IEnumerable (Query generated in steps) that I'm taking in as a param (right after the where clause).

Base on column names List I'm trying create a dynamic select clause.

public static IQueryable<T> AddSelectClause<T>(SearchDto criteria, IQueryable<T> queryable, ControllerStateManager stateManager)
    {
        if (criteria.SelectColumns != null)
        {
            var formattedColumns = string.Join(", ", criteria.SelectColumns);
            queryable.SelectMany(c => $"new({formattedColumns})");
        }

        return queryable;
    }

Obviously this is not working, no exception just returns all columns.

I tried this:

queryable.Select(c => new { c.Id, c.Name });

Intellisense doesn't like this saying: T does not contain a definition for Id (same for name).

That is about my depth of knowledge on Linq, any suggestions would be greatly appreciated

1

There are 1 best solutions below

0
Stef Heyenrath On

You should be able to use:

queryable.SelectMany("new({formattedColumns})");