EF Core - self referencing entity

asp.net-core c# entity-framework-core

Question

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:

System.Data.SqlClient.SqlException (0x80131904): Introducing FOREIGN KEY constraint 'FK_Directory_Directory_SubOfId' on table 'Directory' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

I tried setting ON DELETE to CASCADE but nothing, still the same error. I do not know how to set NO ACTION because mapping does not offer this option.

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);

        }
1
1
3/6/2018 2:13:08 PM

Popular Answer

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.

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.

2
3/6/2018 2:11:52 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow