开发者

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开发者_Python百科 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?


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜