EF 7 多对多关系没有 FK 到连接器 table
EF 7 Many-to-Many relationship no FK to connector table
我正在使用 Entity Framework 7 RC1,我实际上是在尝试创建一个字段,以便我可以持有学生标准(一个学生可以有多个标准,每个标准可以属于多个学生)。按照 asp.net 文档,我有 tables 设置,我在 [=28] 中手动填写了 Student table、Standard table 和 StudentStandard table =] 服务器使用一些虚构的数据。但是,当我在运行时调试 code/view 时,我看到 StudentStandards 字段是 'null' 当我在控制器中执行 getAll 时。我正在使用以下代码访问视图中的此字段:model.Students.StudentStandards.Select(c=>c.StandardId) 但这不提供任何内容。
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
public ICollection<StudentStandard> StudentStandards { get; set; }
}
public class StudentStandard
{
[ForeignKey("Student")]
public int StudentId { get; set; }
public Student Student { get; set; }
[ForeignKey("Standard")]
public int StandardId { get; set; }
public Standard Standard { get; set; }
}
public class Standard
{
public int StandardId { get; set; }
public string StandardName { get; set; }
public ICollection<StudentStandard> StudentStandards { get; set; }
}
这是 table 使用迁移创建后的样子:
我的问题:如何获得此 m:m 关系来存储和检索此数据?
您所追求的称为预加载。默认情况下,任何 EF 查询都将获取实体本身的记录,但不会获取属于它的外键 table 的记录。如果您有兴趣引入相关的 tables 数据,您应该使用 Include()
函数并指定您感兴趣的外键 tables,标准 table在你的情况下。您的 EF Linq 将如下所示:
//context is your DbContext object
context.Students.Include(s => s.Standards).ToList();
我不得不使用以下代码预先加载 table:
context.Students
.Include(a => a.StudentStandards)
.ThenInclude(b => b.Standard);
我正在使用 Entity Framework 7 RC1,我实际上是在尝试创建一个字段,以便我可以持有学生标准(一个学生可以有多个标准,每个标准可以属于多个学生)。按照 asp.net 文档,我有 tables 设置,我在 [=28] 中手动填写了 Student table、Standard table 和 StudentStandard table =] 服务器使用一些虚构的数据。但是,当我在运行时调试 code/view 时,我看到 StudentStandards 字段是 'null' 当我在控制器中执行 getAll 时。我正在使用以下代码访问视图中的此字段:model.Students.StudentStandards.Select(c=>c.StandardId) 但这不提供任何内容。
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
public ICollection<StudentStandard> StudentStandards { get; set; }
}
public class StudentStandard
{
[ForeignKey("Student")]
public int StudentId { get; set; }
public Student Student { get; set; }
[ForeignKey("Standard")]
public int StandardId { get; set; }
public Standard Standard { get; set; }
}
public class Standard
{
public int StandardId { get; set; }
public string StandardName { get; set; }
public ICollection<StudentStandard> StudentStandards { get; set; }
}
这是 table 使用迁移创建后的样子:
我的问题:如何获得此 m:m 关系来存储和检索此数据?
您所追求的称为预加载。默认情况下,任何 EF 查询都将获取实体本身的记录,但不会获取属于它的外键 table 的记录。如果您有兴趣引入相关的 tables 数据,您应该使用 Include()
函数并指定您感兴趣的外键 tables,标准 table在你的情况下。您的 EF Linq 将如下所示:
//context is your DbContext object
context.Students.Include(s => s.Standards).ToList();
我不得不使用以下代码预先加载 table:
context.Students
.Include(a => a.StudentStandards)
.ThenInclude(b => b.Standard);