以下SchoolContext树是否正确?

时间:2019-07-04 05:42:36

标签: .net entity-framework

假设我们有:

public class Student
{
    public int StudentID { get; set; }
    public string Name { get; set; }
}
public class Teacher
{
    public int TeacherID { get; set; }
    public string Name { get; set; }
}
public SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Teacher> Teachers { get; set; }
}

将其理解为下面的树是否正确?

SchoolContext
        |
        |__ DbSet<Student>
        |           |__ An entry1 (includes an Student entity, original values, current values, state of the entity)
        |           |__ An entry2 (includes an Student entity, original values, current values, state of the entity)
        |           |__ ...
        |
        |__ DbSet<Teacher>
                    |__ An entry1 (includes an Teacher entity, original values, current values, state of the entity)
                    |__ An entry2 (includes an Teacher entity, original values, current values, state of the entity)
                    |__ ...

据我所知:

  • 学生实体是Student类的实例。

  • 原始值是我们获取数据后该实例的开始值,例如.Find()方法。

  • 当前值是我们修改后的值。

  • 状态告知实体的当前状态。

1 个答案:

答案 0 :(得分:0)

如果您想与学生老师之间建立联系,请处理许多相关的事情。 示例1:老师可以有很多学生,一个学生可以有很多老师,因此这将是多对多的关系。

这种情况下要创建另一个类

class TeacherStudent
{
    public int StudentID { get; set; }
    public Student Student { get; set; }


    public int TeacherID { get; set; }
    public Teacher Teacher { get; set; }
}

public class Student
{
    public int StudentID { get; set; }
    public string Name { get; set; }
    public List<TeacherStudent> TeacherStudents { get; set; }
}
public class Teacher
{
    public int TeacherID { get; set; }
    public string Name { get; set; }
    public List<TeacherStudent> TeacherStudents { get; set; }
}
  

,并在您的数据库上下文类中重写下面的方法,以便TeacherStudent成为FK关系。

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TeacherStudent>()
            .HasKey(s => new { s.TeacherID, s.StudentID });
    }