3

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?

Cranialsurge
  • 6,104
  • 7
  • 40
  • 39

2 Answers2

2

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

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

Community
  • 1
  • 1
Pauli Østerø
  • 6,878
  • 2
  • 31
  • 48
1

I don't believe you can accomplish what you want with the way you are going about it. In order to create an anonymous type, the shape (i.e. properties) of the type must be known at compile time. Your best bet to do what you want would be to build the select expression by hand (using the expression APIs found in System.Linq.Expressions), then passing in the expression you've built in code into the Select() extension method (and not using the declarative query syntax like you are in your example).

Ultimately, if you get this working, it is most likely the case that you will have to use reflection to access anything from the items of the collection you are getting as you will not know what it will hold until runtime.

Is there a reason you don't want to return the entire object?

Brian Ball
  • 12,268
  • 3
  • 40
  • 51
  • Actually you are right, the select is only a projection on a result set correct? It has no bearing on the performance of the query (in terms of how much data is being returned). I was trying to filter the select clause to restrict what I get back from the query as I wanted to only work with certain properties. – Cranialsurge Jan 26 '11 at 00:09
  • Whether or not the projection affects the database query is completely up to the Linq Provider. I know that Entity Framework (and at least one implementation of NHibernate Linq) does take the select statement into consideration, and will attempt to craft the resulting SQL statement to only pull back what is needed (and will throw an exception if it is unable to do so), but unless you are talking about an obscene amount of data, then I wouldn't worry about optimizing to that level yet. – Brian Ball Jan 26 '11 at 04:13