我是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查询?
答案 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;