c# - 指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束 WEBAPI
问题描述
当我尝试运行我的应用程序时遇到问题。我通过更改方法添加了迁移,并向一个表OnModelCreating
添加了一个属性。ClassId
每次我想运行程序时,我都会收到错误消息
Microsoft.Data.SqlClient.SqlException:在表 'Students' 上引入 FOREIGN KEY 约束 'FK_Students_Classes_ClassId' 可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
无法创建约束或索引。查看以前的错误
第一个实体:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Surename { get; set; }
public int Pesel { get; set; }
public string KeeperName { get; set; }
public int KeeperTelephoneNumber { get; set; }
public virtual List<Book> Books { get; set; } = new List<Book>();
public int? ClassId { get; set; }
public virtual Class? Class { get; set; }
public virtual List<SchoolSubject> SchoolSubjects { get; set; } = new List<SchoolSubject>();
public List<Note> Notes { get; set; } = new List<Note>();
}
第二实体:
public class Class
{
public int Id { get; set; }
public string ClassName { get; set; }
public int EmployeeId { get; set; }
public Employee SupervisingTeacher { get; set; }
public virtual List<Student> Students { get; set; } = new List<Student>();
public virtual List<SchoolSubject> SchoolSubjects { get; set; } = new List<SchoolSubject>();
}
OnModelCreating
方法:
modelBuilder.Entity<Class>()
.HasMany(s => s.Students)
.WithOne(a => a.Class)
.HasForeignKey(s => s.ClassId)
.OnDelete(DeleteBehavior.ClientNoAction);
modelBuilder.Entity<Employee>()
.Property(prop => prop.Name)
.IsRequired().HasMaxLength(20);
modelBuilder.Entity<Employee>()
.Property(prop => prop.SureName)
.IsRequired().HasMaxLength(30);
modelBuilder.Entity<Employee>()
.Property(prop => prop.RoleId)
.IsRequired();
modelBuilder.Entity<Employee>()
.Property(prop => prop.UniqueNumber)
.IsRequired();
modelBuilder.Entity<Employee>()
.Property(prop => prop.ContactTelephoneNumber)
.IsRequired()
.HasMaxLength(9);
解决方案
推荐阅读
- php - CodeIgniter,无法调用库类“模板”的函数
- r - 循环遍历数据框以在 R 中创建绘图
- java - 如何从信号/阵列中切出模式?
- vbscript - Outlook VBScript 签名更改颜色和字体无换行符
- installation - 如何在kali linux上安装hyperion 2.2
- arrays - 在 postgresql 中更新多维数组
- python - 检索张量中 1 的位置或将张量拆分为 1
- html - 如何使用 HTML 将 CSS 中的 DIV 元素居中?
- python - Graph 执行中不允许使用 `tf.Tensor` 作为 Python `bool`。使用 Eager 执行或用 @tf.function 修饰这个函数
- django - DRF 所需的搜索过滤器