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

前端 未结 1 1796
别那么骄傲
别那么骄傲 2021-02-07 10:20

I\'m working on an ASP.NET MVC 6 project with Entity-Framework Core (version \"EntityFramework.Core\": \"7.0.0-rc1-final\") backed by a SQL Server 2012 express DB.<

相关标签:
1条回答
  • 2021-02-07 10:44

    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

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