EF Extensions BulkDelete method doesn't delete with foreign keys

443 views Asked by At

I want to delete an entity which has foreign key relations with other tables.

But I get an error :

The MERGE statement conflicted with the REFERENCE constraint

Any suggestions how to make it work?

context.BulkDelete(entities);
1

There are 1 answers

0
Jonathan Magnan On BEST ANSWER

Unfortunately, there is no way to automatically delete foreign key rows with EF Extensions for security reasons unless you have DELETE CASCADE enabled on your foreign key.

If you wish to delete, you will need to delete the foreign key data yourself first:

context.BulkDelete(entities.Select(x => x.ForeignKeyNavigation);
context.BulkDelete(entities);

or

context.MyForeignKeySets.DeleteRangeByKey(entities.Select(x => x.ForeignKeyID).Distinct());
context.BulkDelete(entities);

or

context.MyForeignKeySets.WhereBulkContains(entities.Select(x => x.ForeignKeyID).Distinct()).DeleteFromQuery();
context.BulkDelete(entities);

There is probably some other way to do it, but there is no automatic way to do it inside our library.