【问题标题】:Tables having one to many relationship generates outer join具有一对多关系的表生成外连接
【发布时间】:2022-09-23 01:39:24
【问题描述】:

我有 2 张桌子

public class Department : DbContext
{
   public int DeptId {get; set;}
   public string DeptName {get; set;}
   public virtual List<Student> Students {get; set;}
}

public class Student: DbContext
{
   public int StudentId {get; set;}
   public string StudentName {get; set;}
   public int DeptId {get; set;}
   public virtual Department Department {get; set;}
}

所以一个部门可以有多个学生 但我想加入并将所有数据转换为以下结构

public class CollegeData
{
   public int DeptId {get; set;}
   public string DeptName {get; set;}
   public List<StudentData> Students {get; set;}
}

public class StudentData
{
   public int StudentId {get; set;}
   public string StudentName {get; set;}
}

我写了下面的查询来获取连接的数据

var data = (from dept in _dbContext.Department 
            select new CollegeData
            {
              DeptId = dept.DeptId,
              DeptName = dept.DeptName,
              Students = (from student in _dbContext.Student
                          where student.DeptId == dept.DeptId
                          select new StudentData
                          {
                             StudentId = student.StudentId,
                             StudentName = student.StudentName
                          }).ToList()
            }).ToList();

但是当我对此进行分析时,它正在创建左连接查询。 在这个用例中我需要内部连接查询

有人可以给我一个方向吗?

  • 在 LINQ 查询中使用 .ToList() 会影响性能,因为服务器无法在一个查询中完成所有操作。

标签: c# sql .net entity-framework


【解决方案1】:

你可以尝试一些东西

  • FK 关系是必需的还是可选的?如果需要关系,请使用 HasRequired.IsRequired(true)。所需的关系可能会解析为内部连接。但是如果属性的类型是 collection ,它可能会转换为 LEFT JOIN

  • 第二个选项是add a null check in the condition 过滤掉空记录,它本质上转换为INNER JOIN。

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 2017-09-05
    • 2012-02-02
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多