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?
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 !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With