比如:
老师表:Teacher
学生表:Student
记住以下几点:
1、多对多关系需要两侧的集合导航属性。 与其他类型的关系一样,它们也可通过约定发现。
public class Teacher { public int Id { get; set; } public string Name { get; set; } public ICollection<Student> Students { get; set; } }
public class Student { public int Id { get; set; } public string Name { get; set; } public ICollection<Teacher> Teachers { get; set; } }
目前都是导航属性,未配置实体外键
学生端设置描述:
builder.HasMany(x => x.Teachers) .WithMany(x => x.Students);
老师端设置描述:
builder.HasMany(x => x.Students) .WithMany(x => x.Teachers);
生成迁移文件:会自动增加一张关联表
var teacher = new Teacher { Name = "李老师", Students = new List<Student> { new Student() { Name = "王同学" }, new Student() { Name = "张同学" } } }; db.Teachers.Add(teacher); db.SaveChanges();
看效果:
var teachers = db.Teachers.Include(x=>x.Students).ToList(); var students = db.Students.Include(x=>x.Teachers).ToList();
关系已经建好,并且查询不需要关心关联表
留下您的脚步
最近评论