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

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


In my Entity Framework 6 code-first project, I have two tables with a many:many relationship.

In Fluent API, I defined the relationship like this:

            .HasMany(e => e.Recipes)
            .WithMany(e => e.Profiles)
            .Map(m => m.ToTable("ProfileRecipe")
            .MapRightKey(new[] { "Recipes_Name" , "Recipes_Prefix" }));

How is it possible to set the cascade on delete to false in this case?


is not available.

Edit 1:

Here is the code for both tables:

public partial class Profile
    public Profile()
        Recipes = new HashSet<Recipe>();

    public int ID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Recipe> Recipes { get; set; }

public partial class Recipe
    public Recipe()
        Profiles = new HashSet<Profile>();

    [Column(Order = 0)]
    public string Name { get; set; }

    [Column(Order = 1)]
    public string Prefix { get; set; }

    public virtual ICollection<Profile> Profiles { get; set; }

Edit 2:

Cascade delete is on

you will see it in the migrationscript:

    c => new
            Profiles_ID = c.Int(nullable: false),
            Recipes_Name = c.String(nullable: false, maxLength: 200),
            Recipes_Prefix = c.String(nullable: false, maxLength: 200),
    .PrimaryKey(t => new { t.Profiles_ID, t.Recipes_Name, t.Recipes_Prefix })
    .ForeignKey("dbo.Profiles", t => t.Profiles_ID, cascadeDelete: true)
    .ForeignKey("dbo.Recipes", t => new { t.Recipes_Name, t.Recipes_Prefix }, cascadeDelete: true)
    .Index(t => t.Profiles_ID)
    .Index(t => new { t.Recipes_Name, t.Recipes_Prefix });
1/8/2019 9:09:11 AM

Accepted Answer

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:

10/1/2015 6:16:50 AM

Popular Answer

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:

    .HasMany(usr => usr.Roles)
    .WithMany(role => role.Users)
    .Map(m => {

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<User>(Role)

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

Related Questions


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