学生类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();
标签:set,Name,get,插入,Add,Teachers,EFCore,public,中多
From: https://www.cnblogs.com/zy8899/p/18365023