ef core 2.2:如何使用外键独立设置级联删除
ef core 2.2: Ho to setup cascade delete with foreign key in dependant
我已经设置了一个代码优先数据库,其中包含一些基本实体,例如 "Participant"、"Organizer" 或 "School"。他们都可能有一个名为 "Person" 的依赖子实体。因为这些人可能属于这些主要实体中的任何一个,所以主要实体持有外键 "PersonId" 和导航 属性 "Person"。
但据我所知,EF 根据外键的位置决定哪个实体是依赖的——在本例中是主要实体——以及哪个是主体——在本例中是 "Person"。
因此,级联删除不起作用,因为我需要它:删除 "Participant" 应该删除它的 "Person"。
我用 [Required] 注释了 "Person" 属性,事实上 DB 声明 "PersonId"-columns 装饰有 cascade-delete-constraint:
CONSTRAINT FK_Participants_Persons_PersonId FOREIGN KEY (PersonId) REFERENCES Persons (Id) ON DELETE CASCADE
但是删除主要实体(带有急切加载的人)并调用 SaveChanges 不会删除人。
那么我怎样才能实现删除他们的主要实体的人?
作为:
What you are describing looks more like TPT inheritance model, which is not currently supported. There is no automatic way to cascade delete in the opposite direction - this comes from relational database rules and has nothing to do with EF Core. So even with the TPT, the deletion of the derived entity will be redirected to deleting the base entity. Simply do the same - instead of deleting (dbContext.Remove) the Participant, Organizer or School instances, delete (Remove) their loaded Person navigation property.
我已经设置了一个代码优先数据库,其中包含一些基本实体,例如 "Participant"、"Organizer" 或 "School"。他们都可能有一个名为 "Person" 的依赖子实体。因为这些人可能属于这些主要实体中的任何一个,所以主要实体持有外键 "PersonId" 和导航 属性 "Person"。
但据我所知,EF 根据外键的位置决定哪个实体是依赖的——在本例中是主要实体——以及哪个是主体——在本例中是 "Person"。
因此,级联删除不起作用,因为我需要它:删除 "Participant" 应该删除它的 "Person"。
我用 [Required] 注释了 "Person" 属性,事实上 DB 声明 "PersonId"-columns 装饰有 cascade-delete-constraint:
CONSTRAINT FK_Participants_Persons_PersonId FOREIGN KEY (PersonId) REFERENCES Persons (Id) ON DELETE CASCADE
但是删除主要实体(带有急切加载的人)并调用 SaveChanges 不会删除人。
那么我怎样才能实现删除他们的主要实体的人?
作为
What you are describing looks more like TPT inheritance model, which is not currently supported. There is no automatic way to cascade delete in the opposite direction - this comes from relational database rules and has nothing to do with EF Core. So even with the TPT, the deletion of the derived entity will be redirected to deleting the base entity. Simply do the same - instead of deleting (dbContext.Remove) the Participant, Organizer or School instances, delete (Remove) their loaded Person navigation property.