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);

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...


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);

Need Your Help

Core-Data: Want to persist new web xml stuff to my data store rather than replace existing

iphone objective-c iphone-sdk-3.0 core-data

I have an application that loads core data, then calls the XML Web Service to get updated data. I basically want my app, rather than to erase all the data and load everything (including new) to per...

Plot a world map with a specified grid with R

r latitude-longitude maptools world-map

I am trying to use wrld_simpl from maptools package in order to plot a piece of world map with a longitude/latitude grid.