Entity Framework Core 5引入了多对多关系,而没有直接创建联接表。这很好,使编码更快,但我遇到了一些挑战。
当处理继承同一个类(人(的两个类(学生/教师(之间的关系时,我在迁移后更新数据库时出错。
Introducing FOREIGN KEY constraint 'FK_Student_TeacherId' on table 'StudentTeacher' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.
当不使用继承类时,多对多关系似乎毫无效果。
public class Person
{
public int Id { get; set; }
public string SchoolName { get; set; }
public int MyProperty { get; set; }
}
public class Teacher : Person
{
public ICollection<Student> Students { get; set; }
}
public class Student : Person
{
public ICollection<Teacher> Teachers { get; set; }
}
public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder.ToTable("Persons").HasKey(k => k.Id);
}
}
public class TeacherConfiguration : IEntityTypeConfiguration<Teacher>
{
public void Configure(EntityTypeBuilder<Teacher> builder)
{
builder.ToTable("Persons");
builder.HasMany(p => p.Students).WithMany(t => t.Teachers);
}
}
public class StudentConfiguration : IEntityTypeConfiguration<Student>
{
public void Configure(EntityTypeBuilder<Student> builder)
{
builder.ToTable("Persons");
}
}
我可以通过将学生或教师的onDelete
更改为ReferentialAction.Restrict
来手动解决问题
但我觉得这个解决方案不好,因为它在Join表中留下了孤立行。
显然,根据删除时的多对多,EF没有好的候选者可以选择进行限制。因此,在配置时必须手动定义关系:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Teacher>()
.HasMany(t => t.Students)
.WithMany(s => s.Teachers)
.UsingEntity<Dictionary<string, object>>(
"Tutelage",
x => x.HasOne<Student>().WithMany().OnDelete(DeleteBehavior.Cascade),
x => x.HasOne<Teacher>().WithMany().OnDelete(DeleteBehavior.Restrict)
);
}