在EFCore中多對多關係的設計資料插入與查詢

一个人走在路上發表於2024-08-17

學生類Student

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public List<Teacher> Teachers { get; set; }=new List<Teacher>();
}

老師類Teacher

public class Teacher
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Student> Students { get; set; }=new List<Student>();
}

實體配置類StudetnConfig

public class StudentConfig : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> builder)
    {
        builder.ToTable("Student");
        builder.HasMany<Teacher>(s =>s.Teachers).WithMany(t => t.Students).UsingEntity(s=>s.ToTable("StudentTeacher"));
    }
}

MyDbContext資料上下文類

 public DbSet<Student> Students { get; set; }

 public DbSet<Teacher> Teachers { get; set; }

資料插入

//新增資料

//多對多
using MyDbContext db = new MyDbContext();
Student s1 = new Student { Name = "S1" ,Age=18 };
Student s2 = new Student { Name = "S2", Age = 19 };
Teacher t1 = new Teacher { Name = "T1" };
Teacher t2 = new Teacher { Name = "T2" };

s1.Teachers.Add(t1);
s1.Teachers.Add(t2);
s2.Teachers.Add(t1);
s2.Teachers.Add(t2);


           

db.Teachers.Add(t1);
db.Teachers.Add(t2);

db.Students.Add(s1);
db.Students.Add(s2);
db.SaveChanges();

資料查詢

var teachers  = db.Teachers.Include(t=>t.Students).ToList();
  foreach (var t in teachers)
 {
     Console.WriteLine("老師名字:"+t.Name);
     foreach (var s in t.Students)
     {
         Console.WriteLine("\t學生名字:"+s.Name+"---年齡: "+s.Age);
     }
 }
 Console.WriteLine("Hello, World!");
 Console.ReadLine();

相關文章