Entity Framework: Delete Object and its related entities

Posted by Waheed on Stack Overflow See other posts from Stack Overflow or by Waheed
Published on 2010-03-18T06:57:59Z Indexed on 2010/03/18 7:01 UTC
Read the original article Hit count: 1067

Hi, 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 red 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 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.

Thanks in advance....

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about c#