Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

c# - Delete Object and its related 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...