LINQ在多个表上连接查询

时间:2015-01-20 11:53:09

标签: c# sql-server linq entity-framework

我一直在努力在多个牌桌上运行linq。

TABLEA

Select all the (courseID, code, title) from courseInstances table

tableB的

select (studyLevel_ID) from Courses table where courseID from tableA = CourseID from tableB. tableB has courseID

表C

Select (StudyLevelDescription) from StudyLevel table where studyLevelID from tableB = studyLevel from tableC.

我相信我需要在表A上左联,因为我需要所有记录

我已经完成了单独的linq工作正常,但很难带来合并结果

CourseInstances结果

var processedCourseInstance = 
(from _courseInstances in _uof.CourseInstances_Repository.GetAll()
           join _courses in _uof.Courses_Repository.GetAll() on _courseInstances.CourseID equals _courses.CourseID
           into a from b in a.DefaultIfEmpty()
           orderby _courseInstances.CourseCode
           select _courseInstances).ToList();

每门课程的StudyLevel结果

 var _CoursesStudyLevel_Lookup = 
  (from _course in _uof.Courses_Repository.GetAll()
   join _studyLevel in _uof.StudyLevel_Repository.GetAll() on _course.StudyLevelId equals _studyLevel.StudyLevelID
   select new {_course.CourseID, _course.StudyLevelId, _studyLevel.LevelDescription  }).ToList();

我已经设法将两个结果组合在一起,但不与CourseInstance表中的LEFT连接组合。这次我使用了LINQPad

from _courseInstances in CourseInstances
join _courses in Courses on _courseInstances.CourseID equals _courses.CourseID
join _studylevel in StudyLevels on _courses.StudyLevelId equals _studylevel.StudyLevelID
orderby _courseInstances.CourseCode
select new {_courseInstances.CourseID, _courseInstances.CourseCode, _courseInstances.CourseTitle, _courseInstances.UCASCode, _courses.StudyLevelId, _studylevel.LevelDescription, _studylevel.SLevelType }

以上SQL版本如下;

SELECT [t0].[CourseID], [t0].[CourseCode], [t0].[CourseTitle], 

[t0].[UCASCode], [t1].[StudyLevelId], [t2].[LevelDescription], [t2].[SLevelType]
    FROM [CourseInstances] AS [t0]
    INNER JOIN [Courses] AS [t1] ON [t0].[CourseID] = ([t1].[CourseID])
    INNER JOIN [StudyLevel] AS [t2] ON [t1].[StudyLevelId] = ([t2].[StudyLevelID])
ORDER BY [t0].[CourseCode]

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想要这样的东西吗?

from _courseInstances in CourseInstances
join c in Courses on _courseInstances.CourseID equals c.CourseID into courses
from _courses in courses.DefaultIfEmpty()
join sl in StudyLevels on _courses.StudyLevelId equals sl.StudyLevelID into studyLevels
from _studylevel in studyLevels.DefaultIfEmtpy()
orderby _courseInstances.CourseCode
select new {
       _courseInstances.CourseID, 
       _courseInstances.CourseCode, 
       _courseInstances.CourseTitle,
       _courseInstances.UCASCode, 
       _courses.StudyLevelId, 
       _studylevel.LevelDescription, 
       _studylevel.SLevelType 
    }
}

您可以使用 into 关键字和 .DefaultIfEmpt()创建LINQ左连接查询。