Qasimali84,
Based on your question I assume the following:
- You have 5 tables in your database, namely [User], [Group], [Role], [GroupRoles], [GroupUsers]
- The table [GroupRoles] links roles to groups and only contains two fields which are the primary keys of the tables [Group] and [Role]
- The table [GroupUsers] links users to groups and only contains two fields which are the primary keys of the tables [Group] and [User]
- The tables [GroupRoles] and [GroupUsers] don't show up as separate entities in the model but are directly represented as navigation properties
Then the code to perform your two queries (Linq to Entities) is the following:
1 using (Entities context = new Entities())
2 {
3 // Display the roles of a certain group
4 var q = (from g in context.Groups
5 where g.Id == 1
6 select g.Roles).FirstOrDefault();
7 foreach(var role in q)
8 {
9 Console.WriteLine(role.RoleName);
10 }
11
12 Console.WriteLine();
13 // Display the roles of a certain user
14 var q2 = (from g in context.Groups
15 where g.Users.Any(u => u.Id == 1)
16 select g.Roles).FirstOrDefault();
17 foreach(var role in q2)
18 {
19 Console.WriteLine(role.RoleName);
20 }
21 }
If you want the source code, just send me a private message with your e-mail address.
Regards,
Christophe
Please mark my reply as an
answer if it helps you.
Check out my blog