Delete an object and related objects

Does anyone know how to delete an object and all objects associated with it.

For example, I have tables, Products, Category, ProductCategory and productDetails, productCategory combines a table of both Product and Category.

I read from http://msdn.microsoft.com/en-us/library/bb738580.aspx that

Deleting a parent also removes all child objects in a restricted relationship. This result will be the same as the CascadeDelete association property for the relationship.

I am using this code:

 Product productObj = this.ObjectContext.Product.Where(p => p.ProductID.Equals(productID)).First(); if (!productObj.ProductCategory.IsLoaded) productObj.ProductCategory.Load(); if (!productObj.ProductDetails.IsLoaded) productObj.ProductDetails.Load(); //my own methods. base.Delete(productObj); base.SaveAllObjectChanges(); 

But I get the error ObjectContext.SaveChanges(); Ie

The relationship is added or removed from the AssociationSet 'FK_ProductCategory_Product'. With capacity limitations, you must also add or remove the corresponding "ProductCategory".

+2
source share
4 answers

Thanks for the answer. I solved my problem. Using the same cascade in EDMX. For an explanation, I answer my question. :)

We must add <OnDelete Action="Cascade"></OnDelete> to the EDMX file in two parts

  • In the SSDL section
  • In the part of CSDL
+7
source

Take a look at this question .

It describes a case of single-level association. If you set the OnDelete action appropriately, there should be no problem deleting all related child objects.

+5
source

In addition, if you look at your edmx file in visual studio, you can select the “association” and select the “End1 OnDelete” property and set “Cascade”.

+3
source

It is worth noting that you need to make sure that the objects are loaded to delete them - I turned on Cascade, but this did not help until I had the required objects loaded (interestingly, I also did not need to turn on Cascade at all in my case). I documented the message details that helped me the most in tracking Entity Framework details to remove a child

0
source

All Articles