Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically generate Includes in entity framework

Well I am not sure if this questions asked before but I have no idea how the search for it. Well this is not an Entity Framework specified question but I am gonna give example using it.

So in EF we need to use .Include("Related Object") to include related data. However what I want to is that write a method that takes a List of strings and returns the entity or entity list with the related objects.

In example

public List<Entity> GetAll(List<string> includes>)
{
     List<Entity> entites = context.Entites;
     foreach(string s in includes)
     {
          entites.Include(s);
     }
     return entites;
}

Obviously above example won't work since I already called out the Entites when I declared the list. But I think it demonstrates the point.

like image 287
Ege Aydın Avatar asked Jul 08 '15 23:07

Ege Aydın


1 Answers

Declare your local variable as DbQuery<Entity>, reassign result of Include call to it and call ToList on it after the loop:

public List<Entity> GetAll(List<string> includes>)
{
     DbQuery<Entity> entites = context.Entites;
     foreach(string s in includes)
     {
          entities = entites.Include(s);
     }
     return entites.ToList();
}
like image 150
MarcinJuraszek Avatar answered Nov 06 '22 14:11

MarcinJuraszek