Cascade Deleting Many-To-Many relationship in entity framework

前提是你 提交于 2019-12-13 06:50:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!