EF中的实体关系

1.一对一关系类型

上图中Student和StudentAddress是一对一(零)的关系,一个学生只能有一个或零个地址。

实体框架将Student实体导航属性添加到StudentAddress实体中,将StudentAddress实体导航属性添加到Student实体中。

StudentAddress类中的StudentID既是PrimaryKey(主键),也是Student类的ForeignKey(外键)。

public partial class Student
{
    public Student() { this.Courses = new HashSet<Course>(); } public int StudentID { get; set; } public string StudentName { get; set; } public Nullable<int> StandardId { get; set; } public byte[] RowVersion { get; set; } //实体导航属性 public virtual StudentAddress StudentAddress { get; set; } } public partial class StudentAddress {   //同时是主键和外键 public int StudentID { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string State { get; set; } //实体导航属性 public virtual Student Student { get; set; } }

2.一对多关系类型

Teacher和Course是一对多的关系。(一个老师可能教多门课程,一门课程只能由一个老师教)

Standard与Teacher实体具一对多的关系。(一个评分级别可能赋予多个老师,一个老师只能有一个评分)

public partial class Standard
{
    public Standard() { this.Teachers = new HashSet<Teacher>(); } public int StandardId { get; set; } public string StandardName { get; set; } public string Description { get; set; } //集合导航属性 public virtual ICollection<Teacher> Teachers { get; set; } } public partial class Teacher { public Teacher() { this.Courses = new HashSet<Course>(); } public int TeacherId { get; set; } public string TeacherName { get; set; } public Nullable<int> TeacherType { get; set; } //外键 public Nullable<int> StandardId { get; set; } //实体导航属性 public virtual Standard Standard { get; set; } }

Standard实体具有集合导航属性 Teachers (请注意它是复数),Teacher中StandardId是Standard的外键。

3.多对多关系类型

Student和Course具有多对多关系。这表示一个学生可以参加许多课程,而一个课程也可以向许多学生讲授。

public partial class Student
{
    public Student() { this.Courses = new HashSet<Course>(); } public int StudentID { get; set; } public string StudentName { get; set; } public Nullable<int> StandardId { get; set; } public byte[] RowVersion { get; set; } //集合导航属性 public virtual ICollection<Course> Courses { get; set; } } public partial class Course { public Course() { this.Students = new HashSet<Student>(); } public int CourseId { get; set; } public string CourseName { get; set; } //集合导航属性 public virtual ICollection<Student> Students { get; set; } }

这两个类都有集合导航属性。

注:实体框架在中间表仅有两个表的主键(只有StudentId和CourseId)时才自动维护多对多关系。当我们给Student添加一个Course或给Course添加一个Student,执行SaveChange()时,EF会在中间表自动会插入对应的StudentId和CourseId。如果中间表包含其他列,那么EDM也会为中间表创建实体,EF不再自动维护中间表,那么我们就需要手动管理多对多实体的CRUD操作。

猜你喜欢

转载自www.cnblogs.com/1016391912pm/p/12032900.html