简体   繁体   English

EF核心-自我参照实体

[英]EF Core - self referencing entity

I have a table that should refer to the same table. 我有一个表应该引用相同的表。 But when I try to update the database schema, it throws me this error: 但是,当我尝试更新数据库架构时,会引发以下错误:

When i try to update the schema, PMC throws this error: 当我尝试更新架构时,PMC会引发此错误:

System.Data.SqlClient.SqlException (0x80131904): Introducing FOREIGN KEY constraint 'FK_Directory_Directory_SubOfId' on table 'Directory' may cause cycles or multiple cascade paths. System.Data.SqlClient.SqlException(0x80131904):在表“目录”上引入外键约束“ FK_Directory_Directory_SubOfId”可能会导致循环或多个级联路径。 Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

I tried setting ON DELETE to CASCADE but nothing, still the same error. 我尝试将ON DELETE设置为CASCADE,但是什么也没有,仍然是相同的错误。 I do not know how to set NO ACTION because mapping does not offer this option. 我不知道如何设置NO ACTION,因为映射不提供此选项。

What with this? 怎么了

Entity: 实体:

public class Directory : BaseEntity
{
    public int ID { get; set; }

    public int? SubOfId { get; set; }

    [ForeignKey("SubOfId")]
    public Directory SubOf { get; set; }

    public virtual ICollection<ImageDirectory> ImageDirectory { get; set; }
}

Model builder: 模型制作者:

 protected override void OnModelCreating(ModelBuilder builder)
        {

            base.OnModelCreating(builder);

...

            builder.Entity<Directory>().HasOne(e => e.SubOf).WithOne().HasForeignKey<Directory>(a => a.SubOfId).OnDelete(DeleteBehavior.Cascade);

        }

This exception isn't due to self-referencing. 此异常不是由于自引用引起的。 You get this when an entity can be deleted via multiple cascade paths. 当可以通过多个级联路径删除实体时,会得到此信息。 Based on the code you've provided, my best guess is that something going on with ImageDirectory and relationships in play there is actually the source of the issue. 根据您提供的代码,我最好的猜测是ImageDirectory和正在发生的关系中发生的事情实际上是问题的根源。

Long and short, you need to investigate your object graph to see where removing one entity type might cause multiple cascades. 总而言之,您需要研究对象图,以了解在哪里删除一种实体类型可能会导致多个级联。 Then, you'll need to shut off some of those cascades to proceed. 然后,您需要关闭其中一些级联才能继续。 There's not much more that can be said to help you, unfortunately, without being able to see all your entities and the relationships between them all. 不幸的是,在没有看到您所有实体以及它们之间的关系的情况下,没有什么可以说对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM