在 LINQ 查询中包含映射 table 属性 引用

Include mapping table property reference with LINQ query

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

Class老师

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
}

ClassClass房间

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

我已经table建立关系b/w那些table。

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; }
}

现在我想从老师class那里访问Class房间class的属性,为此我在老师里添加了一个虚拟ICollection<TeacherClassroom> class,但是我无法获取class房间class的属性的数据。

到目前为止我已经尝试了以下

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

在上面的句子中,我得到 Classroom 属性 as null.

提前致谢。

var teacher = await _context.Teacher.SelectMany(m=> m.TeacherClassroom).FirstOrDefaultAsync(m => m.Teacher_PK == id);

你能试试吗?

“SelectMany() 关键字创建了一个新集合,作为根据公共字段组合两个集合的结果”

您需要包括两个级别:

_context.Teacher.Include(c => c.TeacherClassroom)
                .ThenInclude(tc => tc.Classroom)
                .FirstOrDefaultAsync(m => m.Teacher_PK == id);