简体   繁体   中英

Complex Linq Query on Entity Framework

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!!!

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).

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM