How to cascade deletion in entity?

I have two objects in my model

Car and car

with a ratio of 1: n.

I want to remove the cascade of the essence of the car. upon removal, 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 he is trying to first remove the object of the car, and then parts of the car.
This cannot be done due to a foreign key.

How can I handle this?
I obviously want to remove carPart first and then only the car.
Thanks.

+4
source share
2 answers

You need to specify the database that you want to cascade on deletion, and then the Entity Framework will do what you expect. You can change the behavior of FK if you go to the Relationships screen for a table in SQL Server Management Studio:

Cascade delete in Sql Server Management Studio

+6
source

If you want to remove Cascade, set up cascading deletion at the database level. You get an error because SQL does not allow deletion.

You do not need to do this in the Entity Framework.

+1
source

Source: https://habr.com/ru/post/1447713/


All Articles