Trying to join tables with predicate builder

2.4k views Asked by At

I have two tables that I want to join using predicate builder. In pseudo code, I want to return all StudentSchedule rows, joining with Student on StudentId, where StudentLastName = "Smith".

public class Student
{
    int StudentId {get;set;}
    string StudentFirstName {get;set;}
    string StudentLastName {get;set;}
}
class StudentSchedule
{
    int StudentScheduleId
    int StudentId
    string ClassName
}

I can do it for one entity just fine-

var studentBuilder = PredicateBuilder.True<Student>();

studentBuilder = studentBuilder.And(Student => Student.StudentId == studentId);

var students = context.Students.Where(studentBuilder).ToList();
1

There are 1 answers

0
Robert McKee On

Then you should change your model to something like this:

public class Student
{
    public int StudentId {get;set;}
    public string StudentFirstName {get;set;}
    public string StudentLastName {get;set;}
    public virtual ICollection<StudentSchedule> StudentSchedules {get;set;}
}
class StudentSchedule
{
    public int StudentScheduleId {get;set;}
    public int StudentId {get;set;}
    public string ClassName {get;set;}
    public virtual Student Student {get;set;}
}

Then your query would be:

var students = db.Students
  .Include(s=>s.StudentSchedules)
  .Where(studentBuilder)
  .ToList();

Without predicate builder:

var students = db.Students
  .Include(s=>s.StudentSchedules)
  .Where(s=>s.StudentLastName == "Smith")
  .ToList();

My personal preference is to not repeat the entity type in the properties unless it's an external property, so my model would be like this:

public class Student
{
    public int Id {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public virtual ICollection<StudentSchedule> Schedules {get;set;}
}
class StudentSchedule
{
    public int Id {get;set;}
    public int StudentId {get;set;}
    public string ClassName {get;set;}
    public virtual Student Student {get;set;}
}

Of course you might want a more detailed model that has "Subjects" (Name, Prerequisites, etc), "Classes" (A subject, a classroom, schedules, Staffs), "Students" (FirstName, LastName, Classes), "Staff" (FirstName, LastName, JobTitle, Classes) and "Schedules" (Day of week, start time, end time, Classes).