1.学校
[Table("School")] public partial class School { public School() { Students = new List<Student>(); Teachers = new List<Teacher>(); } [Key] public string SchoolId { get; set; } public string Name { get; set; } public virtual ICollection<Student> Students { get; set; } public virtual ICollection<Teacher> Teachers { get; set; } }
2.学生
[Table("Student")] public partial class Student { public Student() { Teachers = new List<Teacher>(); } [Key] public string StudentId { get; set; } public string Name { get; set; } public string PhoneId { get; set; } public string SchoolId { get; set; } public virtual School School { get; set; } public ICollection<Teacher> Teachers { get; set; } }
3.教师
[Table("Teacher")] public class Teacher { public Teacher() { Students = new List<Student>(); } [Key] public string TeacherId { get; set; } public string Name { get; set; } public string PhoneId { get; set; } public string SchoolId { get; set; } public virtual School School { get; set; } public virtual ICollection<Student> Students { get; set; } }
上面三个数据表映射成的实体类,关系是学校有多个学生和老师,每个学生和老师互相对应多个
关系配置在DbContext的OnModelCreating方法中配置
一对多
modelBuilder.Entity<Student>() .HasRequired(a => a.School) .WithMany(a => a.Students) .HasForeignKey(a=>a.StudentId); modelBuilder.Entity<Teacher>() .HasRequired(a => a.School) .WithMany(a => a.Teachers) .HasForeignKey(a => a.TeacherId);
多对多
modelBuilder.Entity<Teacher>() .HasMany(a => a.Students) .WithMany(a => a.Teachers) .Map ( a => { a.MapLeftKey("TeacherId"); a.MapRightKey("StudentId"); a.ToTable("Teacher_Student"); } );