问题
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...
回答1:
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);
回答2:
Just to update the answers concerning EF6:
If the foreign keys are set, referential integrity should do automatically via the DBMS itself when deleting the parent entities.
If you use code first, as far as I learned in a MVA tutorial, ON DELETE CASCADE is the default behavior set by EF6. If running DB first, you should alter your childtable(s)...
Here is the link: https://mva.microsoft.com/en-US/training-courses/implementing-entity-framework-with-mvc-8931?l=pjxcgEC3_7104984382 In the Video it's mentioned at 20:00 upwards and in the slide presentation it is said on page 14.
Cheers
来源:https://stackoverflow.com/questions/8340354/cascade-deleting-many-to-many-relationship-in-entity-framework