How can i configure model builder to delete all recipes when user is deleted but when recipe is deleted keep the user

394 views Asked by At

This is my model builder right now, but when i delete user it sets recipes userid to null.

  protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ApplicationUser>().HasMany(e => e.Recipes).WithOne(e => e.ApplicationUser)
                .OnDelete(DeleteBehavior.Cascade);

            modelBuilder.Entity<Recipe>().HasOne(e => e.ApplicationUser).WithMany(e=>e.Recipes)

        }
1

There are 1 answers

0
Kay On

I think you've overstated the mapping, you only need to map one entity to the other.

Try to use this one first;

modelBuilder.Entity<ApplicationUser>().HasMany(e => e.Recipes).OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Recipe>().HasOne(e => e.ApplicationUser);

If the above doesn't work, try this one alone;

modelBuilder.Entity<ApplicationUser>().HasMany(e => e.Recipes).OnDelete(DeleteBehavior.Cascade);