asp.net mvc框架之使用EF多对多关系实现

时间:2022-09-18 08:59:14

老师和学生的关系是多对多关系

多对多关系

1.安装EF框架

2.创建Student4实体类和Teacher4实体类

public class Student4
    {
        public int Id { get; set; }
        public string Name { get; set; } 
        public virtual ICollection<Teacher4> Teachers { get; set; } = new List<Teacher4>();
    }
public class Teacher4
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Student4> Students { get; set; } = new List<Student4>();
    }

在进行多对多定义中,要在实体类中添加ICollection<T>的数据类型

3.创建Student4Config配置类和Teacher4Config配置类

public class Student4Config:EntityTypeConfiguration<Student4>
    {
        public Student4Config()
        {
            this.ToTable("T_Students4");
            this.Property(s => s.Name).HasMaxLength(50);
        }
    }
public class Teacher4Config:EntityTypeConfiguration<Teacher4>
    {
        public Teacher4Config()
        {
            this.ToTable("T_Teachers4");
            this.Property(s => s.Name).HasMaxLength(50);
            this.HasMany(t => t.Students).WithMany().Map(m => m.ToTable("T_TeacherStudentRelations").MapLeftKey("TeacherId").MapRightKey("StudentId"));
        }
    }

在创建多对多关系的时候,会创建第三个表,是学生表和老师表的关联表

4.增加多对多数据(多对多的使用)

Student4 stu1 = new Student4();
            stu1.Name = "张三";

            Student4 stu2 = new Student4();
            stu2.Name = "李四";

            Student4 stu3 = new Student4();
            stu3.Name = "王五";

            Teacher4 th1 = new Teacher4();
            th1.Name = "张老师";

            Teacher4 th2 = new Teacher4();
            th2.Name = "李老师";

            TestDbContext tdc = new TestDbContext();
            th1.Students.Add(stu1);
            th1.Students.Add(stu2);
            th2.Students.Add(stu2);
            th2.Students.Add(stu3);

            tdc.Teachers4.Add(th1);
            tdc.Teachers4.Add(th2);
            tdc.SaveChanges();

            Console.WriteLine("ok");
            Console.ReadKey();