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