Delete the object and any associated entities.

c# c#-4.0 entity-framework linq-to-entities


Does anybody know how to remove an object together with every entity that is connected to it?

As an example, I have the following tables: Products, Category, ProductCategory, and productDetails; ProductCategory joins the Product and Category data.

From what I've read in,

Deleting the parent object also deletes all the child objects in the constrained relationship. This result is the same as enabling the CascadeDelete property on the association for the relationship.

Using this code, I

Product productObj = this.ObjectContext.Product.Where(p => p.ProductID.Equals(productID)).First();

if (!productObj.ProductCategory.IsLoaded)

if (!productObj.ProductDetails.IsLoaded)

//my own methods.

But I'm encountering a mistake onObjectContext.SaveChanges(); I.e.,

A relationship is being added or deleted from an AssociationSet 'FK_ProductCategory_Product'. With cardinality constraints, a corresponding 'ProductCategory' must also be added or deleted.

7/6/2015 6:31:52 PM

Accepted Answer

I appreciate the response. My issue has been resolved. EDMX employs the same cascade. I'm responding to my own query for clarification. :)

We must include<OnDelete Action="Cascade"></OnDelete> at two places in the EDMX file

  1. In the SSDL part
  2. The CSDL section
8/1/2011 11:49:26 AM

Popular Answer

Look at the numbers this inquiry.
There is a description of the one-level association situation. There shouldn't be any issues deleting all related child objects if the OnDelete action is properly configured.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow