您的位置:首页 > 其它

实体之间的关系(EF基础系列篇7)

2015-09-12 17:11 495 查看
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),然后你必须得手动去操作,来实现多对多的关系;

我们以XML视图,来打开实体数据模型,可以看到在SSDL中,可以看到StudentCourse EntitySet实体集, CSDL不包含StudentCourse实体集,代替是的,它被映射成在Student和Course的导航属性里面,在MSL(C-S Mapping)中可以看到它在<AssociationSetMapping>节点中



所以,多对多的关系在实体数据模型的C-S mapping部分中,所以当你向Student表中添加一个Course的时候,或者向Course表中添加一个Student的时候,然后你保存的时候,将会把你插入的学生的或者课程的主键添加到StudentCourse表中,所以这个映射不仅方便关联这两个实体,而且方面管理增删查改的操作;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: