首页 > 解决方案 > 指定 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);

标签: c#asp.net-coreentity-framework-core

解决方案


推荐阅读