Reputation: 11
I'm trying to build a linq query, to get all Modules with the Forms of each Module depending on the rights of the current user, so i can build up my program menu on the users log on.
What is the most efficient way to get the result in a single linq query from the following database structure? So I can do the following with the query result:
foreach (var module in PermittedModuls)
{
//do some stuff
.....
foreach(var form in module.Forms)
{
//do some stuff
.....
}
}
I already got some "dirty" solutions to get it, but I'm sure there is a better way to do this.
By the way I'm using Entity Framework 6
EDIT!!!: Sorry guys, i think my question was not clear.
I wand to get only the forms where the user has a permission!!!
Upvotes: 0
Views: 196
Reputation: 203829
Currently, your code basically does what you want, except that you want to indicate that Forms
should be eagerly populated for each item when you execute the original query, rather than lazily performing N round trips to get each of the modules' forms data. To do this, you use Include
:
foreach (var module in PermittedModuls.Include(m => m.Forms))
{
//do some stuff
foreach(var form in module.Forms)
{
//do some stuff
}
}
Upvotes: 0
Reputation: 82096
Without knowing the details about how you plan on filtering the data, you could simplify your code to
var forms = PermittedModules.SelectMany(x => x.Forms);
This would give you all the forms on every module (presuming that's what you want).
Upvotes: 1