简体   繁体   English

在EF中没有联接表的情况下,如何在具有多对多关系的两个表(实体)之间使用LINQ进行JOIN查询?

[英]How can I make a JOIN query with LINQ between two tables (entities) with many-to-many relationship, while there is no joining table in EF?

I didn't explicitly defined the composite table, as EF handle it automatically, but how can query results from one table with the other's Id: take this example: 我没有明确定义组合表,因为EF会自动处理它,但是如何使用另一个ID来查询一个表的结果:

public class Student
{
public int Id {get; set;}
public string Name{get; set;}
public ICollection<Course> Courses {get; set;}
}

public class Course
{
public int Id {get; set;}
public string Name {get; set;}
public ICollection<Student> Students {get; set;}
}

How I can get all courses for the Student with id = 3 I made this query: 我如何获取ID = 3的学生的所有课程,我进行了以下查询:

var studentCourses = from s in context.Students join c in context.Courses on s.Id equals ?? what?

Should I define the joining table? 我应该定义联接表吗?

// Return all courses where at least one student has a specific id.
var studentId = 3;
var courses = context.Courses.Where(x => x.Students.Any(y => y.Id == studentId));

Or 要么

var studentId = 3;
var courses = context.Students.Where(x => x.Id == studentId).SelectMany(x => x.Courses);

Should I define the joining table? 我应该定义联接表吗?

No, unless it contains anything of interest. 不可以,除非其中包含任何有趣的东西。 Does it add any more information than the connection between the tables, such as DateAdded ? 它是否比表之间的连接增加了更多信息,例如DateAdded In that case I would create an entity for the table. 在那种情况下,我将为表创建一个实体。 But not otherwise. 但不是这样。

Why not use property Courses from the Student class: 为什么不使用学生班的物业课程:

List<Course> coursesOfStudent3;
using (var dbContext = new MySchoolDbContext())
{
    coursesOfStudent3 = dbContext.Students
        .Where(student => student.studentId == 3)
        .Single()
        .Courses
        .ToList();
}

You get a problem if there is no student with StudentId == 3. Consider using SelectMany: 如果没有StudentId == 3的学生,则会出现问题。考虑使用SelectMany:

coursesOfStudent3 = dbContext.Students
    .Where(student => student.studentId == 3)
    .SelectMany(student => student.Courses)
    .ToList();

This alternative works if there is no student with StudentId == 3. However it only works if you can guarantee that your Where clause returns only one student, which in case of selection by ID is of course the case. 如果没有StudentId == 3的学生,则此替代方法有效。但是,只有在您可以保证Where子句仅返回一名学生的情况下,该方法才有效,在通过ID选择的情况下,当然是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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