I start to use Entity Framework in a new project, to see if it is valid or no.
But I got stuck in a part where I need to join 5 tables. I am pretty sure that the relationship between them are ok, I can select using .Include(x => x.table)
for only three (because I found on the internet), and I know I will need to Use Join()
, but I don't know how.
The select in SQL is:
SELECT
Module.*
FROM
UserGroup as ug
INNER JOIN
Group as g ON ug.IdGroup = g.IdGroup
INNER JOIN
GroupFunctionality as gf ON g.IdGroup = gf.IdGroup
INNER JOIN
Functionality as f ON gf.IdFunctionality = f.IdFunctionality
INNER JOIN
Screen as s ON f.IdScreen = s.IdScreen
INNER JOIN
Module as m ON s.IdModule = m.IdModule
WHERE
ug.IdUser = 1
Using LINQ to Entities and assuming DbSet context property names are same as table names, here is the query using C# expression:
from ug in db.UserGroup
join g in db.Group on ug.IdGroup equals g.IdGroup
join gf in db.GroupFuncionality on g.IdGroup equals gf.IdGroup
join f in db.Funcionality on gf.IdFuncionality equals f.IdFuncionality
join s in db.Screen on f.IdScreen equals s.IdScreen
join m in db.Module on s.IdModule equals m.IdModule
where ug.IdUser == 1
select m
If you want to use Join
method with lambda expression style, here is multiple join syntax (converted from above syntax with LINQPad):
db.UserGroup.Join(db.Group, ug => ug.IdGroup, g => g.IdGroup, (ug, g) => new { ug = ug, g = g })
.Join(db.GroupFuncionality, temp0 => temp0.g.IdGroup, gf => gf.IdGroup, (temp0, gf) => new {temp0 = temp0, gf = gf})
.Join(db.Funcionality, temp1 => temp1.gf.IdFuncionality, f => f.IdFuncionality, (temp1, f) => new {temp1 = temp1, f = f})
.Join(db.Screen, temp2 => temp2.f.IdScreen, s => s.IdScreen, (temp2, s) => new {temp2 = temp2, s = s})
.Join(db.Module, temp3 => temp3.s.IdModule, m => m.IdModule, (temp3, m) => new {temp3 = temp3, m = m})
.Where(temp4 => temp4.temp3.temp2.temp1.temp0.ug.IdUser == 1)
.Select(temp4 => temp4.m)
CMIIW.
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.