2

I'm working with dynamic queries using LINQ on Entity Framework. To query some tables by user input filters, we are using PredicateBuilder to create conditional WHERE sections. That works really great, but the number of columns returned are fixed.

Now, if we need the user to select which columns he needs in their report, besides their filters, we are in trouble, as we don't know how to do dynamic myQuery.Select( x => new { ... }) as we do for Where clause.

How can we achieve something like this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Romias
  • 13,783
  • 7
  • 56
  • 85

1 Answers1

1

A bit of searching reveals that this is tricky. Anonymous types are created at compile time, so it is not easy to create one dynamically. This answer contains a solution using Reflection.emit.

If possible, I would recommend just returning something like a IDictionary<,> instead.

Community
  • 1
  • 1
Thom Smith
  • 13,916
  • 6
  • 45
  • 91
  • I ended up using this: https://github.com/thiscode/DynamicSelectExtensions that internally uses Reflection.Emit(). I did some changes, for my special needs (the code that uses that Select). – Romias Oct 31 '13 at 17:13