Entity Framework 6 fluent api delete cascade on n:n relationship

c# ef-fluent-api entity-framework-6

Accepted Answer

I discovered the solution: Those cascading deletes were brought on byManyToManyCascadeDeleteConvention . To stop this convention from causing cascade deletes for link tables, remove it:

modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
107
10/1/2015 6:16:50 AM

Popular Answer

I concur with Ebram Khalil that a smart alternative is to turn it off for a single table. However, I would set it up in OnModelCreating because I like to adhere as closely as possible to the automatically constructed migrations:

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

If both needed to be blocked (which makes sense in this example), I believe this retains the delete going in the opposite direction, so an identical call would need to be performed beginning withEntity<User>(Role)

Naturally, this is a very long time after the question was posed. Thus, it might not have been appropriate in 2012.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow