How to delete a record with a foreign key constraint?

前端 未结 4 501
小蘑菇
小蘑菇 2020-12-19 02:48

Started a new ASP.NET MVC 3 application and getting the following error:

The primary key value cannot be deleted because references to this key stil

4条回答
  •  青春惊慌失措
    2020-12-19 03:15

    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()
                .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);
    

提交回复
热议问题