How to delete a record with a foreign key constraint?

Found the solution:

public class FoodJournalEntities : DbContext
{
    public DbSet<Journal> Journals { get; set; }
    public DbSet<JournalEntry> JournalEntries { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Journal>()
               .HasOptional(j => j.JournalEntries)
               .WithMany()
               .WillCascadeOnDelete(true);
        base.OnModelCreating(modelBuilder);
    }
}

Source


If you delete a record from a table(lets say "blah"), which has other relationships with other tables (xyz,abc). By default, the database will prevent you from deleting a row in "blah" if there are related rows in one of the other tables.
Solution #1:
You can manually delete the related rows first,this may require a lot of work.
Solution #2:
an easy solution is to configure the database to delete them automatically when you delete a "blah" row.

Follow this open your Database diagram,and click on the properties on the relationship

enter image description here

In the Properties window, expand INSERT and UPDATE Specification and set the DeleteRule property to Cascade.
enter image description here

Save and close the diagram. If you're asked whether you want to update the database, click Yes.

To make sure that the model keeps entities that are in memory in sync with what the database is doing, you must set corresponding rules in the data model. Open SchoolModel.edmx, right-click the association line between "blah" and "xyz", and then select Properties.

In the Properties window, expand INSERT and UPDATE Specification and set the DeleteRule property to Cascade.

Solution and images taken from http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-2


In EF Core (3.1.8), the syntax is a bit different than the accepted answer but the same general idea, what worked for me is below:

modelBuilder.Entity<Journal>()
            .HasMany(b => b.JournalEntries)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade);

In your query to select the item to delete or remove from the database you want to make sure that you are explicitly including the items as well, otherwise it will continue to throw a FK error, something like below.

var item = _dbContext.Journal.Include(x => x.JournalEntries).SingleOrDefault(x => x.Id == id);