1

我在 EF Code First Architecture 中有以下架构。

班主任

public class Teacher
{
[Key]
public int Teacher_PK { get; set; }
public string Name { get; set; }
public int Age { get; set; }        
public virtual ICollection<TeacherClassroom> TeacherClassroom { get; set; } // I have added this to access classroom class's property
}

课堂教室

public class Classroom
{
[Key]
public int Classroom_PK { get; set; }
public string ClassName { get; set; }
public int ClassStrength { get; set; }
}

我已经制作了一张表格来建立与这些表格之间的关系。

public class TeacherClassroom
{
[Key]
public int TecherClassroom_PK { get; set; }

[ForeignKey("Teacher_FK")]
public virtual Teacher Teacher { get; set; }

[Required]
public int Teacher_FK { get; set; }

[ForeignKey("Classroom_FK")]
public virtual Classroom Classroom { get; set; }

[Required]
public int Classroom_FK { get; set; }
}

现在我想从教师类访问课堂类的属性,因为我ICollection<TeacherClassroom>在教师类中添加了一个虚拟,但我无法获取课堂类属性的数据。

到目前为止,我已经尝试过

var teacher = await _context.Teacher.Include(c=>c.TeacherClassroom.Select(y=>y.Classroom))
                .FirstOrDefaultAsync(m => m.Teacher_PK == id);

在上面的句子中,我将 Classroom Property 设为null.

先感谢您。

4

2 回答 2

1

您需要包括两个级别:

_context.Teacher.Include(c => c.TeacherClassroom)
                .ThenInclude(tc => tc.Classroom)
                .FirstOrDefaultAsync(m => m.Teacher_PK == id);
于 2022-02-08T17:15:53.523 回答
0
var teacher = await _context.Teacher.SelectMany(m=> m.TeacherClassroom).FirstOrDefaultAsync(m => m.Teacher_PK == id);

你能试一下吗?

“SelectMany() 关键字根据公共字段组合两个集合来创建一个新集合”

于 2022-02-08T17:11:53.310 回答