How to configure two ManyToMany relationships and avoid MultipleCascade Problem?

41 Views Asked by At

I have a TableA, TableB and TableC.

Both TableA and TableB have one to many relationships with TableC. Also they have ManyToMany relationship between each other through TableATableB.

 public class TableC
 {
     public Guid Id {get;set;}

     public TableA TableA{ get; set; }
     public Guid TableAId { get; set; }

     public TableB TableB{ get; set; }
     public Guid TableBId { get; set; }
 }

public class TableA
{
    public Guid Id { get; set }

    public ICollection<TableATableB> TableATableBs{ get; set; } = [];
    public ICollection<TableC> TableCs { get; set; } = [];

}

public class TableB
{
    public Guid Id { get; set }

    public ICollection<TableATableB> TableATableBs{ get; set; } = [];
    public ICollection<TableC> TableCs { get; set; } = [];

}

 public class TableATableB
 {
     public Guid Id { get; set; }

     public TableA TableA { get; set; }
     public Guid TableAId { get; set; }

     public TableB TableB { get; set; }
     public Guid TableBId { get; set; }

 }

No Fluent API configuration is written. All the defaults of EfCore migrations. The problem is I'm getting

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

It will work if I configure Cascade OnDelete to Restrict for both TableA, and TableB in the TableC. But I don't want that. I want to TableC to be deleted if any of TableA or TableB are deleted.

Why am I getting this error? Is this because of ManyToMany relationship between TableA and TableB? But logically if any of them get deleted, then it should cascade to the intermediary table(TableATableB), and not to the other one...

P.S. There is some other fields in TableC, so it is a standalone Entity, not used as intermediary for ManyToMany connection between TableA and TableB. I have a dedicated table for that.

0

There are 0 best solutions below