问题描述
我开始在新项目中使用Entity Framework,以查看其是否有效.
I start to use Entity Framework in a new project, to see if it is valid or no.
但是我陷入了需要加入5张桌子的部分.我很确定他们之间的关系还可以,我可以选择使用 .include(x => x.table)
的三个(因为我在互联网上找到了),而且我知道将需要使用 Join()
,但我不知道如何.
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.
SQL中的选择是:
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
推荐答案
对实体使用LINQ,并假定DbSet上下文属性名称与表名称相同,这是使用C#表达式的查询:
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
如果要使用具有lambda表达式样式的 Join
方法,以下是多种联接语法(使用LINQPad从上面的语法转换):
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.
这篇关于将SQL Select转换为实体框架跨五个表的联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!