How to delete a record with a foreign key constraint?

江枫思渺然 提交于 2019-11-29 09:56:41

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

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

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

Hasnain Mehmood

I found it...

Go TO SQL Server

Make his Database diagrammed

Right click on relation ship line between parent and child and open the property of it.

Set INSERT And Update Specification and simply set DELETE RULE TO CASCADE.

Remember No code is required in Project FOR this PURPOSE and simply debug and enjoy it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!