如何禁用级联删除在EF code-一个链接表?级联、链接、EF、code

2023-09-02 12:02:30 作者:涐的心ヽ上了鎖

我想禁用级联删除与实体框架code-第一链接表。例如,如果许多用户有很多角色,我尝试删除一个角色,我想这删除被阻止的除非的当前没有与该角色相关联的用户。我已经删除了级联删除约定在我的 OnModelCreating

I want to disable cascade deletes for a link table with entity framework code-first. For example, if many users have many roles, and I try to delete a role, I want that delete to be blocked unless there are no users currently associated with that role. I already remove the cascade delete convention in my OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    ...
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

然后我设置的用户角色链接表:

And then I set up the user-role link table:

modelBuilder.Entity<User>()
    .HasMany(usr => usr.Roles)
    .WithMany(role => role.Users)
    .Map(m => {
        m.ToTable("UsersRoles");
        m.MapLeftKey("UserId");
        m.MapRightKey("RoleId");
    });

然而,当EF创建数据库,它创建了一个级联删除的外键关系,如:

Yet when EF creates the database, it creates a delete cascade for the foreign key relationships, eg.

ALTER TABLE [dbo].[UsersRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.UsersRoles_dbo.User_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[UsersRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.UsersRoles_dbo.Role_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Role] ([RoleId])
ON DELETE CASCADE
GO

我怎么能阻止EF产生这种级联删除?

How can I stop EF generating this delete cascade?

推荐答案

我得到了答案。因为 ManyToManyCascadeDeleteConvention :-)这些级联删除正在建立。你需要从创建级联删除此公约prevent它删除了链接表:

I got the answer. :-) Those cascade deletes were being created because of ManyToManyCascadeDeleteConvention. You need to remove this convention to prevent it from creating cascade deletes for link tables:

modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();