如何使用LINQ连接多个表

时间:2016-06-17 15:13:34

标签: c# asp.net-mvc linq join

我试图用LINQ连接三个表。我的SQL工作如下:

Select j.Id, u.FirstName , u.LastName, u.Role
From    Job j  
    left  join JobTranslator as jt on j.Id = jt.JobId
    left  join JobRevisor as jr on j.Id = jr.JobId
    left  join [User] as u on  jt.UserId = u.Id OR jr.UserId = u.Id
Where   u.Id = someID;

我可以使用以下两个联接来使用它:

 IQueryable<Job> jobs =
                from j in _db.Jobs

                join jr in _db.JobRevisors on j.Id equals jr.JobId into jrs
                from jrResult in jrs.DefaultIfEmpty()

                join u in _db.Users on jrResult.UserId equals u.Id into jrU
                from jrUResult in jrU.DefaultIfEmpty()

                where jrUResult.Id == userId
                orderby j.Id
                select j;

但是当我尝试加入我最后需要的表时,它的工作情况并不像下面那样。

IQueryable<Job> jobs =
                from j in _db.Jobs

                join jt in _db.JobTranslators on j.Id equals jt.JobId into jts
                from jtResult in jts.DefaultIfEmpty()

                join jr in _db.JobRevisors on jtResult.Id equals jr.JobId into jrs
                from jrResult in jrs.DefaultIfEmpty()

                join u in _db.Users on jrResult.UserId equals u.Id into jrU
                from jrUResult in jrU.DefaultIfEmpty()

                join u in _db.Users on jtResult.UserId equals u.Id into jtU
                from jtUResult in jtU.DefaultIfEmpty()

                where jtUResult.Id == userId

                orderby j.Id

                select j;

任何人的想法?

1 个答案:

答案 0 :(得分:8)

来自Linq - left join on multiple (OR) conditions

myarray = myarray.loc[business_day]