级联删除实体框架中的多对多关系 [英] Cascade Deleting Many-To-Many relationship in entity framework

查看:215
本文介绍了级联删除实体框架中的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有三个表:

 文章:ArticleID(PK)
标签:TagiID )
ArticleTagMapping:ArticleID(FK,PK),TagID(FK,PK)

ArticleTagMapping具有复合主键。这导致了我的实体模型中的多对多关系如预期。我已经设置了两个外键关系,以便在数据库中删除。



我试图通过C#代码删除文章。这个错误出来...

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

我想删除该文章的所有ArticleTagMapping条目,而不影响标签条目。
我不想删除标签表中的任何条目,只能删除映射表中的条目。需要帮助...

解决方案

您没有向我们显示错误。但是我怀疑你有关系的问题,阻止删除实体。



在SQL Server Management studio中,右键单击 ArticleTagMapping table-> code> - >右键单击 - > 关系...

现在选择文章之间的关系表和 ArticleTagMapping 表。展开 INSERT和UPDATE规范,并将两个规则更改为 Cascade 。通过这样做,每当您删除文章时, ArticleTagMapping 表中的所有相关关系将自动删除:

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


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

解决方案

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

这篇关于级联删除实体框架中的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆