你的位置:首页 > ASP.net教程

[ASP.net教程]实体之间的关系(EF基础系列篇7)


EF实体之间的关系分为:

1.一对一;

2.一对多;

3.多对多;

 

一对一关系:

Student和StudentAddress之间:

public partial class Student  {    public int StudentID { get; set; }    public string StudentName { get; set; }    public Nullable<int> StandardID { get; set; }    public string RowVersion { get; set; }      public virtual Standard Standard { 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; }  }

一对多关系:

上面很多,就举出一例吧,Teacher和Standard

 public partial class Standard  {    public Standard()    {      this.Students = new HashSet<Student>();      this.Teachers = new HashSet<Teacher>();    }      public int StandardID { get; set; }    public string StandardName { get; set; }    public string Description { get; set; }      public virtual ICollection<Student> Students { 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> StandardID { get; set; }    public string TeacherType { get; set; }      public virtual ICollection<Course> Courses { get; set; }    public virtual Standard Standard { get; set; }  }

多对多关系:

Student和Course之间:

 public partial class Student  {    public Student()    {      this.Course = new HashSet<Course>();    }      public int StudentID { get; set; }    public string StudentName { get; set; }    public Nullable<int> StandardID { get; set; }    public string RowVersion { get; set; }      public virtual Standard Standard { get; set; }    public virtual StudentAddress StudentAddress { get; set; }    public virtual ICollection<Course> Course { get; set; }  }

 public partial class Course  {    public Course()    {      this.Student = new HashSet<Student>();    }      public int CourseID { get; set; }    public string CourseName { get; set; }    public string Location { get; set; }    public Nullable<int> TeacherID { get; set; }      public virtual Teacher Teacher { get; set; }    public virtual ICollection<Student> Student { get; set; }  }

注意:需要注意的是,EF支持多对多的关系,仅仅是关联表(这里是StudentCourse),不包含Student和Course主键之外,任何其他的列的表。如果关联表包含了其他的列,比如删除日期(Datedelete),然后你必须得手动去操作,来实现多对多的关系;

我们以

 

所以,多对多的关系在实体数据模型的C-S mapping部分中,所以当你向Student表中添加一个Course的时候,或者向Course表中添加一个Student的时候,然后你保存的时候,将会把你插入的学生的或者课程的主键添加到StudentCourse表中,所以这个映射不仅方便关联这两个实体,而且方面管理增删查改的操作;