0

Let's say I have a table that I can query with EF + LINQ like this:

    var results = dbContext.MyTable.Where(q => q.Flag = true);

Then, I know that if I want to limit the columns returned, I can just add a select in that line like this:

    var results = dbContext.MyTable
            .Select(model => new { model.column2, model.column4, model.column9 })
            .Where(q => q.Flag == true);

The next step that I need to figure out, is how to select those columns dynamically. Said another way, I need to be able to select columns in a table withoutknowing what they are at compile time. So, for example, I need to be able to do something like this:

    public IEnumerable<object> GetWhateverColumnsYouWant(List<string> columns = new List<string{ "column3", "column4", "column999"})
    {
            // automagical stuff goes here.
    }

It is important to keep the returned record values strongly typed, meaning the values can't just be dumped into a list of strings. Is this something that can be accomplished with reflection? Or would generics fit this better? Honestly, I'm not sure where to start with this.

Thanks for any help.

quakkels
  • 11,676
  • 24
  • 92
  • 149
  • you could look at this for a start : http://stackoverflow.com/questions/606104/how-to-create-linq-expression-tree-with-anonymous-type-in-it – Raphaël Althaus May 22 '13 at 21:09

1 Answers1

0

I think you want some dynamic linq, Im no expert on this but i THINK it will go something like this

public static IEnumerable<object> GetWhateverColumnsYouWant(this IQueriable<T> query, List<string> columns = new List<string{ "column3", "column4", "column999"})
{
    return query.Select("new (" + String.Join(", ", columns) + ")");
}

See scott Gu's blog here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx and this question System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)

You could probably also do this by dynamically composing an expression tree of the columns youre wanting to select but this would be substantially more code to write.

Community
  • 1
  • 1
undefined
  • 33,537
  • 22
  • 129
  • 198
  • The problem that I'm running into is that once I run `var result = db.TableObject.Select("new (ID, Name)");` I can't follow it up with `result.FirstOrDefault();` or a `ToList()` or anything like that to actually execute the sql query. – quakkels May 29 '13 at 16:52
  • @quakkels glad you got this sorted :) I've been meaning to take a bit more of a look but haven't had time yet – undefined May 30 '13 at 20:20