Cannot get cascading delete to work in EF

I have an entity framework model on top of an SQL server backend.

I have two tables: Processing and Segment. Processing is one-to-many with a segment. In the database, I have a cascading delete setting with respect to the foreign key between the tables, so that when processing is deleted, all its corresponding segments are also deleted. This work when I delete the treatment directly from the database.

In the EF model, I changed the "End1 OnDelete" property to "Cascade". However, when I try to remove the treatment, I get the following error:

"The operation failed: the connection cannot be changed because one or more properties of the foreign key are not NULL. When changing the relation to the related property of the foreign key, it is set to null. If the foreign key does not support null values, you need to define a new relation for the foreign property the key must be assigned another non-zero value, or an unrelated object must be deleted. "

Here is the code where I delete the cure:

public bool Delete(Treatment myTreatment) { bool result = false; using (myEntities myObjectContext = new myEntities()) { if (myTreatment.Treatment_ID == 0) { result = true; } else { if (myTreatment.EntityState == System.Data.EntityState.Detached) { myObjectContext.Treatments.Attach(myTreatment); } myObjectContext.ObjectStateManager.ChangeObjectState(myTreatment, System.Data.EntityState.Deleted); } result = (myObjectContext.SaveChanges() != 0); } return result; } 

What am I doing wrong?

EDIT Here is the CSDL for the Association for @Fauxtrot.

 <Association Name="TreatmentSegment"> <End Type="tamcModel.Treatment" Role="Treatment" Multiplicity="1" > <OnDelete Action="Cascade" /> </End> <End Type="tamcModel.Segment" Role="Segment" Multiplicity="*" > </End> <ReferentialConstraint> <Principal Role="Treatment"> <PropertyRef Name="Treatment_ID" /> </Principal> <Dependent Role="Segment"> <PropertyRef Name="Treatment_ID" /> </Dependent> </ReferentialConstraint> </Association> 
+4
source share
1 answer

Having played around a bit with this, I came across the following solution. I am posting it here, so others in the future who may have this problem may see a solution.

I changed the following line:

 myObjectContext.ObjectStateManager.ChangeObjectState(myTreatment, System.Data.EntityState.Deleted); 

For this:

 myObjectContext.DeleteObject(myTreatment); 

And now it works ....

hmmm ....

0
source

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


All Articles