我有簡單的「圖形」表示存儲在數據庫中。有Node
實體,它有ID
,Label
和相鄰節點列表。實體框架6,映射連接表的級聯刪除
public class Node
{
[Key]
public int Id { get; set; }
[StringLength(128)]
public string Label { get; set; }
public virtual ICollection<Node> AdjacentNodes { get; set; }
}
然後在OnModelCreating
數據庫上下文類,我有:
modelBuilder.Entity<Node>()
.HasMany(n => n.AdjacentNodes)
.WithMany()
.Map(n => n.MapLeftKey("From").MapRightKey("To").ToTable("NodeEdge"));
現在,當我想刪除它已經任何關係的任何節點,我得到約束錯誤:
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.
連接表看起來像這樣:
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])
);
有什麼辦法如何在連接表約束上添加ON DELETE CASCADE
- 所以當我刪除節點時它會清除所有引用? (...並且保持模型簡單而沒有連接表實體)
似乎'RemoveRange'有助於避免約束錯誤,但仍然不會清除連接表,儘管引用的項目已被刪除(...有時我真的不知道EF正在做什麼) –
流利的API添加WillCascadeOnDelete(真正)? –
不幸的是,WillCascadeOnDelete不適用於多對多的關係。 –