简体   繁体   中英

How to query in .NET EF Core with Linq?

我的 EF 图

Hi, I have the relationship table / model like the picture above.

A Teacher can take multiple trainings. A Training/Course can be a FormalTraining or not. A Teacher may have many students.

Now I want to get list of Students whose teacher has taken a Course where IsFormalTraining == true.

How do I do that in .NET EF Core 2.2?

Edited:

models:

Teacher
{
    int Id;
    string Name;
    ICollection<TeacherStudent> students ; 
}

TeacherStudent{
    int Id;
    int TeacherId;
    int StudentId;
}

Student {
    int Id;
    string Name;
}

TeacherTraining{
    int Id;
    int TeacherId;
    int CourseId;
    DateTime StartDate;
}

Course {
    int Id;
    string Name;
}

I'm making a few assumptions based on your classes so you might need to test and tweak, but I imagine it'll look something like this:

var students = 
    context.Students.Where(s => 
      context.Teachers.Any(t => 
        t.Students.Any(st => st.StudentId == s.Id) && context.TeacherTraining.Any(tt => 
            tt.TeacherId == t.Id && 
            context.Course.Any(c => tt.CourseId == c.Id && c.IsFormalTraining))));

I'm not able to debug this without rigging up a ton of stuff, so you might have to step through it. You could also break this up into more queries, it'll be easy to read and etc, but it probably won't be very efficient (granted, I don't know how efficient this is without running a test).

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