Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Querying a Many to Many to Many relationship

I have a database where Users can belong to multiple Roles and Roles can have multiple Permissions. Both relationships are many to many. I want query and generate a list of the Rermissions a User has. I am trying to accomplish this by querying the Roles table to see what Roles the User is a member of and then I want to query and see what distinct Permissions each Role contains. However I can't seem to get the LINQ correct.

var permissions = RoleRepository.Get()
    .Where(x => x.Users.Contains(user))
    .Select(x => x.Permissions);

The above code gives me a list of list of Permissions, I just want a list of Permissions. Is there anyway (in LINQ) to take the union of all these lists? Or is there a better way to accomplish this?

like image 517
Stefan Bossbaly Avatar asked Dec 28 '12 16:12

Stefan Bossbaly


1 Answers

Use SelectMany Instead, SelectMany flattens queries that return lists of lists

So Try this :

var permissions = RoleRepository.Get().Where(x => x.Users.Contains(user))
                                .SelectMany(x => x.Permissions);

Hope this will help !!

like image 167
Kundan Singh Chouhan Avatar answered Oct 25 '22 22:10

Kundan Singh Chouhan