Home > Software design >  What will be the DB Context code for executing this SQL?
What will be the DB Context code for executing this SQL?

Time:08-14

I am new to DbContext and I am confused about how to join tables using DbContext - can someone tell me the code equivalent to this SQL?

Select * 
From AssignedCourses 
Join Students On StudentRollnumber = Students.StudentRollno 
Join Courses On Courses.CourseId = AssignedCourses.AssignedCourseId

CodePudding user response:

With EF you don't seldom need joins. Provided your relations are setup right in your backend, tools generate the models for you using navigational properties. Even without tools, it is easy to create models with navigatinal properties. That query could be written in different ways depending on your real needs. With navigational properties, generally you don't have the middle bridging table, but directly reference to Courses from Student (courses that a student is enrolled) or Students from Course (Students that are enrolled to that course). Assuming you want primarily the Students and the Courses they were enrolled to:

var result = ctx.Students;
// or preload them the Courses as well
var result = ctx.Students.Include(s => s.Courses);
  • Related