How to disable cascade delete for link tables in EF code-first?

前端 未结 3 1418
说谎
说谎 2020-11-27 17:57

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 del

3条回答
  •  感情败类
    2020-11-27 18:20

    I agree with Ebram Khalil that turning it off for a single table is a good option. I like to stick as close to the automatically built migrations as I can, however, so I would set it up in OnModelCreating:

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

    I believe this preserves the delete going the other direction, so if both needed to be blocked (makes sense in this example) a similar call would need to be made starting with Entity(Role)

    Of course, this comes ages after the question was asked. So it may not have been valid in 2012.

提交回复
热议问题