Entity Framework 6 Code-First cascade delete on self referencing entity

前端 未结 1 1468
臣服心动
臣服心动 2021-01-19 14:37

I have an entity:

public class Section : SortableEntity
{
    private ICollection
_sections; public ICollection
Sections
相关标签:
1条回答
  • 2021-01-19 14:55

    If you Google your question you'll see a gazillion other people have the same issue, the reason is because SQL Server can not handle cascade deletes on self referencing entities and I've found no solution within entity framework that does it simply by setting some property. The only way I know to emulate a cascade delete on self referencing entities using code first is to write a recursive method that iterates through the children as you collect primary keys, foreign keys, and level of recursion information. Once this list is built, loop through it ordered by level of recursion in descending order, in each iteration you get all records for that level of recursion, loop though that collection and delete them one at a time. I did this with a stored procedure that returned this list using a recursive common table expression. I hope this helps.

    0 讨论(0)
提交回复
热议问题