Entity Framework 6: Code First Cascade delete

假装没事ソ 提交于 2019-11-29 09:19:27

It depends on whether you want Entity Framework to delete the children, or you want the database to take care of it.

If you want EF to generate a delete statement for all the children and execute those before deleting the parent, you have to load all the children into memory first.

So you can't simply create a "dummy" entity with just the key populated, and expect the children to be deleted.

For that to work, you have to let the database handle the deletion.

The foreign key on the child table would have to have cascade deletes enabled however. If that's the case, Entity Framework just creates a delete statement for the parent, and the database knows to delete the children as well.

Entity Framework creates a foreign key with cascade deletes enabled by default, if the relationship is required, like in your case. (Foreign key can't be null).

If you have created the database yourself, you have to remember to enable it.

I think it's better to override the OnModelCreating method and add this code.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<JohnsChildTable>()
               .HasRequired(t=>t.JohnsParentTable)
               .WithMany(t=>t.JohnsChildTables)
               .HasForeignKey(d=>d.JohnsParentTableId)
               .WillCascadeOnDelete(true);

            base.OnModelCreating(modelBuilder);
}

I've set to true WillCascadeOnDelete(true)

In Visual Studio open the model file. Right click on the Parent-Child relationship and select Properties.

On the End1 OnDelete property the value will probably be None. The other option is Cascade; set it to that. Now deleting a Parent will cascade the deletes to its children.

Cheers -

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