I have three tables, Roles, Users, and connecting table.
I want to show all roles, and for particular user it's name (or if he is member of it). SQL below with nested joins (for SQL Server).
How to write LINQ in C#? Could someone please help to translate SQL -> LINQ? I'm using Entity Framework 6 for .Net 4.7.2, and same names for the tables under db context: DbSet<tRole> tRoles
create table tRole (id int, name varchar(255))
insert into tRole values (1,'user')
insert into tRole values (2,'admin')
create table tUser (id int, name varchar(255))
insert into tUser values (1,'john')
insert into tUser values (2,'sam')
insert into tUser values (3,'amanda')
create table tRoleUser (roleId varchar(255), userId varchar(255))
insert into tRoleUser values (1,1) -- user john
insert into tRoleUser values (1,2) -- user sam
insert into tRoleUser values (2,2) -- admin sam
-- amanda not user, and not admin
select
r.name [role name],
ru.userid,
u.name [user name]
from tRole r
left join tRoleUser ru
join tUser u on u.id = ru.userid and u.name = 'john'
on r.id = ru.roleid
Result for john:
user 1 john
admin NULL NULL
Result for amanda:
user NULL NULL
admin NULL NULL
Result for sam:
user 2 sam
admin 2 sam