简体   繁体   English

如何在实体框架中级联删除?

[英]How to cascade delete in entity framework?

I have two objects in my model 我的模型中有两个对象

Car and carPart 汽车和汽车零件

with 1:n relationship. 与1:n的关系。

I want to delete cascade the entity car. 我想删除cascade实体车。 when I delete i get the following exception : 当我删除时,我得到以下异常:

 The operation failed: The relationship could not be changed because one or 
 more of the foreign-key properties is non-nullable. When a change is made 
 to a relationship, the related foreign-key property is set to a null value. 
 If the foreign-key does not support null values, a new relationship must 
 be defined, the foreign-key property must be assigned another non-null value, 
 or the unrelated object must be deleted.

I think it tries to delete the car object first and then the car parts. 我认为它首先尝试删除汽车对象然后再删除汽车零件。
Which is imposiible due to the foreign key. 由于外键,这是不可能的。

How do I handle this ? 我该如何处理?
I want, obviously to delete the carPart first and then only the car. 我想,显然先删除carPart然后再删除汽车。
Thanks. 谢谢。

You'll need to tell the database that you want to cascade on delete, and then Entity Framework will do what you expect. 您需要告诉数据库您要在删除时级联,然后实体框架将执行您期望的操作。 You can change the FK behavior if you go to the Relationships screen for a table in SQL Server Management Studio: 如果转到SQL Server Management Studio中的表的“ Relationships屏幕,则可以更改FK行为:

Sql Server Management Studio中的级联删除

If you want Cascade delete then setup cascade delete at database level. 如果要删除Cascade,请在数据库级别设置级联删除。 You are getting error because SQL is not allowing to deletion. 您收到错误,因为SQL不允许删除。

You don't have to do it in Entity Framework. 您不必在Entity Framework中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM