I want to disable cascading deletes for the link table with the first entity code. For example, if many users have many roles, and I'm trying to remove a role, I want this removal to be blocked if there are no users who are currently associated with this role. I already delete the cascade exception convention in my OnModelCreating :
protected override void OnModelCreating(DbModelBuilder modelBuilder) { ... modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
And then I set up a table of links to the user role:
modelBuilder.Entity<User>() .HasMany(usr => usr.Roles) .WithMany(role => role.Users) .Map(m => { m.ToTable("UsersRoles"); m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); });
However, when EF creates a database, it creates a delete cascade for foreign key relationships, for example.
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
How can I stop the EF creation of this delete cascade?
Jez Dec 04 '12 at 14:44 2012-12-04 14:44
source share