I have simple "graph" representation stored in database. There is Node
entity which has it's ID
, Label
and list of adjacent nodes.
public class Node
{
[Key]
public int Id { get; set; }
[StringLength(128)]
public string Label { get; set; }
public virtual ICollection<Node> AdjacentNodes { get; set; }
}
Then in OnModelCreating
on database context class, I have:
modelBuilder.Entity<Node>()
.HasMany(n => n.AdjacentNodes)
.WithMany()
.Map(n => n.MapLeftKey("From").MapRightKey("To").ToTable("NodeEdge"));
Now, when I want to delete any node which has already any relation, I get constraint error:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.NodeEdge_dbo.Nodes_From". The conflict occurred in database "master", table "dbo.NodeEdge", column 'From'. The statement has been terminated.
Join table looks like this:
CREATE TABLE [dbo].[NodeEdge] (
[From] INT NOT NULL,
[To] INT NOT NULL,
CONSTRAINT [PK_dbo.NodeEdge] PRIMARY KEY CLUSTERED ([From] ASC, [To] ASC),
CONSTRAINT [FK_dbo.NodeEdge_dbo.Nodes_From] FOREIGN KEY ([From]) REFERENCES [dbo].[Nodes] ([Id]),
CONSTRAINT [FK_dbo.NodeEdge_dbo.Nodes_To] FOREIGN KEY ([To]) REFERENCES [dbo].[Nodes] ([Id])
);
Is there any way how to add ON DELETE CASCADE
on join table constraints - so it will clear up all references when I'm deleting nodes? (... and keeping model simple without having join table entity)