Entity Framework Querying a Many to Many to Many relationship

.net, c#, entity-framework, many-to-many, sql-server

Solution

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

Problem

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?

Original source

Related problems