Search code examples
c#entity-frameworkmany-to-manycascading-deletes

Cascade Deleting Many-To-Many relationship in entity framework


I have three tables in my database:

Articles: ArticleID (PK) 
Tags: TagiID (PK)
ArticleTagMapping: ArticleID(FK,PK), TagID(FK,PK)

ArticleTagMapping has a composite primary key. This resulted in a many-to-many relationship in my entity model as expected. I have set both the foreign key relationships to cascade on delete in database.

I am trying to delete Article via C# code. This errors out...

var ArticleToDelete = context.Articles.SingleOrDefault(x => x.ArticleID == ArticleID);
context.Articles.DeleteObject(ArticleToDelete);
context.SaveChanges();

I want to delete all the ArticleTagMapping entries for that article without affecting the Tags entries. I DO NOT want to Delete any entries from Tags table, but only entries from the mapping table. Need help here...


Solution

  • You have not shown us the error. But I suspect you're having problems with relationships that prevent deleting the entity.

    in SQL Server Management studio, right click on ArticleTagMapping table-> Design->Right click->Relationships...
    Now select the relationship between Articles table and ArticleTagMapping table. Expand INSERT And UPDATE Specification and change both Rules to Cascade. By doing so, whenever you delete an article, all the related relationships in ArticleTagMapping table will be deleted automatically:

    var article = context.Articles.SingleOrDefault(a => a.ID == articleID);
    context.DeleteObject(article);