您可以通过一到一对多关系的许多部分中的值过滤实体框架DBSET吗?

发布于 2025-01-27 13:23:30 字数 807 浏览 4 评论 0原文

我试图通过一个与多个关系的一部分中的值来过滤dbset。例如,我需要获取整个学生列表。每个学生都可以有很多课。我需要根据学生是否有特定的课程过滤。

在上下文文件中;

modelBuilder.Entity<Student>()
            .HasMany(e => e.Classes)
            .WithOne(x => x.Student)
            .HasForeignKey(m => m.StudentId);

在服务文件中,我可能会通过诸如性别之类的属性过滤学生,这就是为什么我使用iqueryable&lt; student&gt;

IQueryable<Student> studentQuery = _context.Students;
studentQuery = studentQuery.Where(x => x.Gender == "MALE");
var students = await studentQuery
                         .Include(c => c.Classes.Where(c => c.className == "GYM"))
                         .ToListAsync();

发生了什么事是,当我尝试过滤班级时,它会返回全部学生,但只列出了班级健身房。我需要的是所有班级中的所有学生的清单。

最终的输出是针对Web API。我希望我对此充分解释。感谢您的帮助。

I am trying to filter a DbSet by a value that is in the many part of a one to many relationship. For example, I need to get the entire list of students. Each student can have many classes. I need to filter students based off of if they have a specific class.

In the context file I have;

modelBuilder.Entity<Student>()
            .HasMany(e => e.Classes)
            .WithOne(x => x.Student)
            .HasForeignKey(m => m.StudentId);

In the service file, I might filter student by an attribute such as gender which is why I am using an IQueryable<Student>:

IQueryable<Student> studentQuery = _context.Students;
studentQuery = studentQuery.Where(x => x.Gender == "MALE");
var students = await studentQuery
                         .Include(c => c.Classes.Where(c => c.className == "GYM"))
                         .ToListAsync();

What is happening is that when I try to filter the classes, it returns all students but only lists the class gym. What I need is a list of all of the students where one of there classes is GYM.

The eventual output is for a Web API. I hope that I explained this well enough. Thank you for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

新雨望断虹 2025-02-03 13:23:30

如果您想让学生在的任何课程中是“健身房”:

var students = await studentQuery
        .Include(c => c.Classes)
        .Where(s => s.Classes.Any(c => c.className == "GYM")))
        .ToListAsync();

If you want students where any of their classes is "GYM":

var students = await studentQuery
        .Include(c => c.Classes)
        .Where(s => s.Classes.Any(c => c.className == "GYM")))
        .ToListAsync();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文