【问题标题】:Error when creating Database using Entity Framework Core使用 Entity Framework Core 创建数据库时出错
【发布时间】:2021-06-08 22:23:43
【问题描述】:

当我尝试使用 Entity Framework Core 创建数据库时,出现以下错误

Introducing FOREIGN KEY constraint 'FK_StudentAnnouncements_Students_StudentId' on table 'StudentAnnouncements' 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.

StudentStudentAnnouncements 之间存在一对多关系。我的Student 实体的代码如下

public class Student
{
    public int Id { get; set; }
    public virtual ICollection<StudentAnnouncement> StudentAnnouncements { get; set;}
}

我的StudentAnnouncement 实体有以下代码

public class StudentAnnouncement
{
    public int Id { get; set; }
    public int StudentId { get; set; }
    public virtual Student Student { get; set; }
}

当我使用 dotnet ef database update 创建迁移并更新数据库时,我收到此错误。

【问题讨论】:

    标签: asp.net-core entity-framework-core


    【解决方案1】:

    级联删除意味着当一个Student被删除时,StudentAnnouncements表中所有引用该Student的行也将被删除,这样就没有指向不存在的Student的Student Announcement。您在这里所拥有的是级联删除将对多个实体产生影响的场景。换句话说,如果一个学生被删除,除了 StudentAnnouncements 之外的其他一些表也将删除行,而 SQL Server 不喜欢这种歧义。您必须选择您真正想要删除的内容以及要保留的内容。

    可以使用 Fluent API 在 DbContext OnConfiguring() 方法中更改级联删除的默认行为。您可以在此处了解该配置: https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete#configuring-cascading-behaviors

    【讨论】:

    • 这是否意味着我必须手动检查相关的子实体并删除它们,然后才能删除相关的父实体
    【解决方案2】:

    StudentAnnouncements上名为FK_StudentAnnouncements_Students_StudentId的外键问题。

    选择以下解决方案之一:

    (1) 删除数据库中的外键FK_StudentAnnouncements_Students_StudentId,重新运行Entity Framework Core 脚手架。

    (2)指定ON DELETE NO ACTION

    (3)指定UPDATE NO ACTION

    示例语法

    CREATE TABLE child_table
    ( 
     col_1 data_type [ NULL | NOT NULL ],
     col_2 data_type [ NULL | NOT NULL ],
     …
    
     CONSTRAINT fk_name
      FOREIGN KEY (child_col_1, child_col_2, … child_col_n)
      REFERENCES parent_table (parent_col_1, parent_col_2, … parent_col_n) 
      ON DELETE CASCADE 
      [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
    );
    

    让我知道结果。

    【讨论】:

    • 感谢大家的帮助。但我决定在删除父记录之前先编写删除子记录的方法。我正在使用删除限制
    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2021-06-30
    • 2017-07-10
    • 2021-04-04
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多