外键约束可能会导致循环或多个级联路径,但只能在一个项目中

时间:2019-06-14 17:44:53

标签: entity-framework-core

我已经解决了SO上的其他问题,但这些问题在我的实例中都没有帮助,因此请不要将其标记为重复。我从文档中下载并运行了该方法,以获取多对多链接表。示例项目有

public class Book {
    [Key]
    public int BookId { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public ICollection<BookCategory> BookCategories { get; set; }
}
public class Category {
    [Key]
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public ICollection<BookCategory> BookCategories { get; set; }
}
public class BookCategory {
    public int BookId { get; set; }
    public Book Book { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

  modelBuilder.Entity<BookCategory>()
        .HasKey(bc => new { bc.BookId, bc.CategoryId });
    modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Book)
        .WithMany(b => b.BookCategories)
        .HasForeignKey(bc => bc.BookId);
    modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Category)
        .WithMany(c => c.BookCategories)
        .HasForeignKey(bc => bc.CategoryId);
OnModelCreating

。这样可以正常工作,并创建正确的迁移文件,看起来像这样

table.ForeignKey(
     table.ForeignKey(
    name: "FK_BookCategory_Book_BookID",
    column: x => x.BookID,
    principalTable: "Book",
    principalColumn: "BookID",
    onDelete: ReferentialAction.Cascade);
table.ForeignKey(
    name: "FK_BookCategory_Category_CategoryID",
    column: x => x.CategoryID,
    principalTable: "Category",
    principalColumn: "CategoryID",
    onDelete: ReferentialAction.Restrict);

将代码复制到我的项目中并添加迁移会创建相同的迁移文件。但是,当我尝试更新数据库时,出现错误

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

将两个table.ForeignKey(语句换行意味着错误指向FK_BookCategory_Book_BookID,并且只有其中之一可以成功更新数据库。

有什么想法为什么迁移可以在一个项目中进行而不能在另一个项目中进行?

1 个答案:

答案 0 :(得分:0)

tag = Tag.objects.get_or_create(name='django') # applying it to user: UserTag.objects.get_or_create(user=user, tag=tag) # find user tags: user.tags.all() # find tag users: tag.users.all() 中,我删除了

protected override void OnModelCreating(ModelBuilder modelBuilder) {

并用

替换
.HasForeignKey(bc => bc.BookId);

所以看起来像这样。

.OnDelete(DeleteBehavior.Restrict);

这将删除级联部分,因此一切正常。我已经在SQL Management Studio和代码中测试了从每个表中删除记录的过程,并且没有代码会级联任何删除操作,这表示我很高兴。