How to dynamically generate Includes entity structure

Well, I'm not sure if these questions have been asked before, but I have no idea how to look for this. Well, this is not a asked question in the Entity Framework, but I will give an example using it.

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

In the example

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

Obviously, the above example will not work, since I already called Entites when I declared the list. But I think that demonstrates the point.

+5
source share
1 answer

Declare your local variable as DbQuery<Entity> , reassign the result of the Include call, 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(); } 
+4
source

All Articles