3

Am using Entity Framework to run a query on a table. However, i need to get select columns only.

class MyEvent
{
    public string Name { get; set; }
    public int Id { get; set; }
    virtual Stage EventStage { get; set; }
    ..... more columns .....
}

class Stage
{
    public string Name { get; set; }
    public string Location { get; set; }
    ..... more columns .....
}

I can write an IQueryable to return these as

dbContext.MyEvents
         .Select(s =>
            new {
                    Name = s.Name,
                    Id = s.Id,
                    EventStage = new
                    {
                        Name = s.EventStage.Name,
                        Id = s.EventStage.Id
                    }
                }
           )
           .ToList();

This works as expected, giving me just those columns am interested in.

Now, I need to construct that 'Select' call dynamically using Expression tree, something like here.

How can I achieve that? Is it feasible to construct an anynomous object, like above, via expressions?

EDIT: The use case for me is that I have a generic dB context class which takes a list of columns as strings to be fetched. In the past, we were returning all columns, ignoring that input list. So, now I need to dynamically generate the select statement to return only the required subset of columns, which can either be done via anonymous object or a dynamically created DTO.

Thanks

Community
  • 1
  • 1
sppc42
  • 2,994
  • 2
  • 31
  • 49
  • Could you make an example of the usage that you want? – Michael Aug 18 '16 at 15:35
  • Anonymous classes are real classes in compile time. Therefore to make lambda in runtime you should also construct class in runtime. Use reflection to create class type and fields inside it, then construct query with it (I haven't done it myself because it is weird) – Szer Aug 18 '16 at 15:43
  • @Michael: updated the use case – sppc42 Aug 18 '16 at 15:51
  • Why do you need to return an anonymous type? Why can't you create a strongly typed object? – Benjamin Drolet Aug 18 '16 at 17:32
  • I deleted my answer because @BenjaminDrolet is right. Use DTO objects to return only what is needed from your model. Anonymous types seems the easy way, but also think about readability of your code and documentation of you API. – Michael Aug 19 '16 at 08:37

2 Answers2

0

Maybe you can use something like the ToDynamic method from here:

https://gist.github.com/volak/20f453de023ff75edeb8

A possible usecase for this problem: Let the user select the columns to display and query only those selected columns, so you don't query always the whole entity from the database.

Lars
  • 6,421
  • 1
  • 23
  • 24
-3

Define a strongly typed object and return that. I would avoid using a dynamic object.

Note: you can't return an anonymous object.