【问题标题】:EF 7 Many-to-Many relationship no FK to connector tableEF 7 多对多关系没有 FK 到连接器表
【发布时间】:2016-05-12 01:00:48
【问题描述】:

我正在使用 Entity Framework 7 RC1,我实际上是在尝试创建一个字段,以便我可以保存学生标准(一个学生可以有多个标准,每个标准可以属于多个学生)。按照 asp.net 文档,我设置了表格,并使用一些组成的数据在 SQL Server 中手动填写了 Student 表、Standard 表和 StudentStandard 表。但是,当我在运行时调试代码/视图时,当我在控制器中执行 getAll 时,我发现 StudentStandards 字段为“null”。我正在使用以下代码访问视图中的此字段: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; }
}

这是使用迁移创建表后的样子:

我的问题:我如何获得这种 m:m 关系来存储和检索这些数据?

【问题讨论】:

    标签: entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    您所追求的称为急切加载。默认情况下,任何 EF 查询都将获取实体本身的记录,但不会获取属于它的外键表的记录。如果您有兴趣引入相关表数据,您应该使用Include() 函数并指定您感兴趣的外键表,即您的案例中的标准表。您的 EF Linq 将如下所示:

    //context is your DbContext object
    context.Students.Include(s => s.Standards).ToList();
    

    【讨论】:

    • 我可以包括 StudentStandards 连接器表,但我没有像上面那样对标准表进行自动检测。看看我的学生实体,这确实是有道理的,因为本身没有标准字段。你能帮我验证一下吗?谢谢
    • 感谢@dotNet。结合您的答案和其他网络帖子找出答案
    • @DerDee:哪个属性?
    • 学生,所以要覆盖链接表(StudentStandards)
    • @DerDee:我真的不确定你在问什么。当您从数据库中导入模型时,EF 设计器会针对 Student 表生成 Studnents 属性。
    【解决方案2】:

    我必须使用以下代码预先加载表格:

        context.Students
       .Include(a => a.StudentStandards)
       .ThenInclude(b => b.Standard);
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多