Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to obtain select fields in a linq query

I am using Linq for my queries and would like to be able to get a list of properties I want returned in the "select" portion using reflection. I've tried the following to no avail:

string[] paramList = new[]{"AppId","Name"};
var query =
                from entity in
                    _ctx.App
                select new {entity.GetType().GetProperties().Where(prop=>paramList.Contains(prop.Name) )};

What am I missing here?

like image 407
Cranialsurge Avatar asked Jan 24 '26 05:01

Cranialsurge


1 Answers

When working with reflection inside a EF query you would need to write the expression yourself. Look at these existing question for more information

  • Help with Linq and Generics. Using GetValue inside a Query
  • How to reflect over T to build an expression tree for a query?
  • IQueryable<> dynamic ordering/filtering with GetValue fails

The problem is not Linq itself, but because your query is parsed into an Expression Tree which Entity Framework doesn't understand.

like image 100
Pauli Østerø Avatar answered Jan 26 '26 20:01

Pauli Østerø