如何使用带有EF 6的Linq扩展方法编写子查询

时间:2014-12-29 09:06:24

标签: c# linq entity-framework subquery extension-methods

我是linq的新手,我有3张这些列的表。

Trainee (ID, TraineeName)
Course (ID, CourseName)
TraineeCourseEnrollment (TraineeID, CourseID, EnrolledDate)

我使用此查询创建了一个存储过程来获取未注册的课程。

select * 
from Course 
where ID not in (select CourseID 
                 from TraineeCourseEnrollment 
                 where TraineeID = @traineeid);

如何使用扩展方法将相应的linq查询写入此SQL查询?

3 个答案:

答案 0 :(得分:0)

您必须执行两个查询,首先检索要排除的ID,然后选择第二个以获取实际课程:

var excludeIDs = db.TraineeCourseEnrollments.Where(w => w.TraineeID == traineeid).Select(s => s.CourseID);
var courses = db.Courses.Where(w =>!excludeIDs.Contains(w.ID)).ToList();

答案 1 :(得分:0)

这样的事情:

扩展方法:

int traineeid = ...;

var query = dc.Courses
              .Where(c => ! dc.TraineeCourseEnrollments
                              .Where(o => o.TrainessID == traineeid)
                              .Select(o => o.CourseID)
                              .Contains(c.ID));

LINQ查询:

int traineeid = ...;

var query =    
    from c in dc.Courses
    where !(from o in dc.TraineeCourseEnrollments
            where o.TraineeID == traineeid
            select o.CourseID)    
           .Contains(c.ID)    
    select c;

答案 2 :(得分:0)

var prospectus = new [] 
{ 
    new { CourseId = "C1", CourseName = "Database" },
    new { CourseId = "C2", CourseName = "HCI" },
    new { CourseId = "C3", CourseName = "Op Systems" },
    new { CourseId = "C4", CourseName = "Programming" }
};

var enrollment = new []
{
    new { TraineeID = "T1", CourseId = "C1", Date = new DateTime(2014, 12, 01) },
    new { TraineeID = "T2", CourseId = "C1", Date = new DateTime(2014, 12, 05) },
    new { TraineeID = "T1", CourseId = "C3", Date = new DateTime(2014, 12, 01) }
};

var notMatchingQueryStyle = from c in prospectus
                            where !enrollment.Any(r => c.CourseId == r.CourseId)
                            select c;

Resharper惹我生气,简化"这使用All代替Any,请参见:

var notMatchingQueryStyle = from c in prospectus
                            where enrollment.All(r => c.CourseId != r.CourseId)
                            select c;