Delete the object and any associated entities.

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


Does anyone know how to delete an object and all of it's related entities.

For example I have tables, Products, Category, ProductCategory and productDetails, the productCategory is joining table of both Product and Category.

I have read from that

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.

I am using this code:

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 am getting an error on ObjectContext.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

Thanks for the reply. I have solved my problem. Using the same cascade in EDMX. For the explanation i am answering my own question. :)

We have to add <OnDelete Action="Cascade"></OnDelete> in EDMX file at two portions

  1. In SSDL portion
  2. In CSDL portion
8/1/2011 11:49:26 AM

Popular Answer

Take a look at this question.
There the case of one-level association is described. In case you set the OnDelete action appropriately there should be no problems to delete all associated child objects.

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