Linq-to-SQL中的多个JOIN

时间:2018-10-31 14:47:25

标签: c# sql linq linq-to-sql

我正在尝试使用linq-to-sql(连接3个不同的表)进行以下查询:

select * from tbl_round r 
inner join tbl_election e on r.fk_election_id = e.election_id
inner join tbl_meeting m on m.meeting_id = e.fk_meeting_id

这是我到目前为止的内容,但不正确:

from round in db.tbl_rounds
join meeting in db.tbl_meetings on election.fk_meeting_id equals meeting.meeting_id 
join election in db.tbl_elections on round.fk_election_id equals election.election_id 
select round;

我得到的错误是名称“ election”在当前上下文中不存在。

2 个答案:

答案 0 :(得分:2)

您可能必须像这样重新排序连接语句

from round in db.tbl_rounds
join election in db.tbl_elections on round.fk_election_id equals election.election_id
join meeting in db.tbl_meetings on election.fk_meeting_id equals meeting.meeting_id  
select round;

答案 1 :(得分:2)

因为在声明之前使用了“选举”。

from round in db.tbl_rounds
join meeting in db.tbl_meetings on -->election<--.fk_meeting_id equals meeting.meeting_id 
join -->election<-- in db.tbl_elections on round.fk_election_id equals election.election_id 
select round;

在这种情况下,您将需要更改查询的顺序。

查询应如下所示:

from round in db.tbl_rounds
join election in db.tbl_elections on round.fk_election_id equals election.election_id
join meeting in db.tbl_meetings on election.fk_meeting_id equals meeting.meeting_id 
select round;