Delete Object and its related entities

13,701

Solution 1

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

Solution 2

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.

Solution 3

Also, If you look at your edmx file in visual studio, you can select the "association" and select "End1 OnDelete" property and set to "Cascade".

Share:
13,701
Waheed
Author by

Waheed

Results-driven professional that has demonstrated capabilities to learn new languages and products with over nine year of experience in the computer software consulting company. Exceptional record of increasing operating efficiency and boosting profitability through expertise in database administration, computer software engineering, operations management, and staff supervision. Proven track of designing and implementing flexible solutions which support frequent UI and functionality changes.

Updated on June 05, 2022

Comments

  • Waheed
    Waheed almost 2 years

    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 http://msdn.microsoft.com/en-us/library/bb738580.aspx 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)
        productObj.ProductCategory.Load();
    
    if (!productObj.ProductDetails.IsLoaded)
        productObj.ProductDetails.Load();
    
    //my own methods.
    base.Delete(productObj);
    base.SaveAllObjectChanges();
    

    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.

  • Kevin Gauthier
    Kevin Gauthier about 14 years
    This is generally right (+1), but you should really have a DB cascade if you do this.