Achille Depla
Achille Depla

Reputation: 107

Introducing FOREIGN KEY constraint ... may cause cycles or multiple cascade paths - Entity Framework

I'm new to Entity Framework and I've tried to fix this for multiple hours now but I'm now at a complete loss.

Could anybody be so kind to point out what I'm missing here?

I get this error when I try to run Update-Database:

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

I try to turn the cascade delete off in OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ContainerActie>()
      .HasOne(c => c.Locatie)
      .WithMany(c => c.ContainerActies)
      .HasForeignKey(c => c.LocatieId)
      .OnDelete(DeleteBehavior.Restrict);
}

But it doesn't seem to have any effect.

public class ContainerActie : SQLModel
{
    [Category("DB")]
    [Key]
    public int ContainerActieId { get; set; }

    [Category("Info")]
    public Container Container { get; set; }

    [Category("Info")]
    public Actie Actie { get; set; }

    [Category("Info")]
    public Relatie Relatie { get; set; }

    [Category("Info")]
    public int LocatieId { get; set; }

    [Category("Info")]
    public Locatie Locatie { get; set; }

    [Category("Info")]
    public DateTime DateTime { get; set; }
}

public class Locatie : SQLModel
{
    [Category("DB")]
    [Key]
    public int LocatieId { get; set; }

    [Category("Info")]
    [Required]
    public string Naam { get; set; }

    [Category("Info")]
    public string? Adres { get; set; }

    [Category("Info")]
    public string? Gemeente { get; set; }

    [Category("Info")]
    public string? Postcode { get; set; }

    [Category("Info")]
    public string? Tel { get; set; }

    [Category("Info")]
    public string? Commentaar { get; set; }

    [Category("Info")]
    public List<ContainerActie>? ContainerActies { get; set; }
}

Upvotes: 3

Views: 8662

Answers (2)

I also ran into a similar error when creating my database tables and although you can solve this problem by explicitly defining it in your OnModelCreating, it could be solved easily just by adding [DeleteBehavior(DeleteBehavior.ClientSetNull)] to the foreign properties e.g:

[Category("Info")]
[DeleteBehavior(DeleteBehavior.ClientSetNull)]
public Actie Actie { get; set; }

For join tables add:

[DeleteBehavior(DeleteBehavior.ClientCascade)]    

instead.

Upvotes: 0

Amirhossein Ghk
Amirhossein Ghk

Reputation: 119

It's because the foreign key LocatieId is not nullable, If the key is not nullable the related object must be deleted, and circular relations don't allow that.

Upvotes: 4

Related Questions