简体   繁体   中英

How to write sub queries using Linq extension methods with EF 6

I'm new to linq and I have 3 tables with these columns.

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

I created a stored procedure to get un-enrolled courses using this query.

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

How to write the corresponding linq query to this SQL query using extension methods?

You will have to do two queries, first to retrieve the IDs that you want to exclude and the second to get actual courses:

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

Something like this:

Extensions methods:

int traineeid = ...;

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

LINQ query:

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;
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 nags me to "simplify" this using All instead of Any , go figure:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM