Entity Framework Core Code-First: Cascade delete on a many-to-many relationship

时间秒杀一切 提交于 2019-12-04 03:10:21
borisdj

First I see you have set City and Address relationship with DeleteBehavior.Restrict and you say: '//I don't want to delete the City when I delete an Address'.
But you don't need Restrict here, because even with DeleteBehavior.Cascade City will not be deleted. You are looking it from the wrong side. What Cascade here does is when a City is deleted all addresses belonging to it are also deleted. And that behavour is logical.

Secondly your many-to-many relationship is fine. When deleting Person its links from PersonAddress Table will automatically be deleted because of Cascade. And if you want also to delete Addresses that were connected only to that Person you will have to do it manually. You actually have to delete those Addresses before deleting Person is order to know what to delete.
So logic should be following:
1. Query through all record of PersonAddress where PersonId = person.Id;
2. Of those take only ones that have single occurance of AddressId in PersonAddress table, and delete them from Person table.
3. Now delete the Person.

You could do this in code directly, or if you want database to do it for you, trigger could be created for step 2 with function: When row from PersonAddress is about to be deleted check if there are no more rows with same AddressId in that PersonAddress table in which case delete it from Address table.

More info here:
How to cascade delete over many to many table
How do I delete from multiple tables using INNER JOIN in SQL server

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