代码优先中禁用链接表的级联删除

代码优先中禁用链接表的级联删除

本文介绍了如何在 EF 代码优先中禁用链接表的级联删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想禁用实体框架代码优先的链接表的级联删除.例如,如果许多用户有多个角色,而我尝试删除一个角色,我希望该删除被阻止除非当前没有与该角色关联的用户.我已经在我的 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,这些级联删除被创建.您需要删除此约定以防止它为链接表创建级联删除:

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>();

这篇关于如何在 EF 代码优先中禁用链接表的级联删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 16:38