[英]How to delete a row in a table and all its foreign key relationships with Entity Framework?
I have table called "Categories" 我有一个名为“类别”的表格
Which has a relationship with this table 哪个与此表有关系
How can I for a example delete the "ForumTest" category and all the threads related to it in the second table? 例如,如何在第二个表中删除“ ForumTest”类别以及与其相关的所有线程?
EDIT: This is my current code that only works with categories without relationships 编辑:这是我当前的代码,仅适用于没有关系的类别
[HttpPost]
public ActionResult DeleteCategory(int? id)
{
Category category = db.Categories.Find(id);
db.Threads.RemoveRange(category.Threads);
db.Categories.Remove(category);
db.SaveChanges();
return RedirectToAction("Categories");
}
You need to config your relationship with cascading delete . 您需要使用级联删除配置您的关系。 Override OnModelCreating
method in your context and add this: 在您的上下文中覆盖OnModelCreating
方法,并添加以下内容:
modelBuilder
.Entity<Thread>()
.HasRequired(s => s.Category)
.WithMany(r => r.Threads)
.HasForeignKey(s=>s.CategoryId)
.WillCascadeOnDelete(true);
Category category = db.Categories.Find(id);
db.Threads.RemoveRange(category.Threads);
db.Categories.Remove(category);
db.SaveChanges();
After this Remove all related table data like. 之后,删除所有类似的表数据。
var categoryDetail = relatedtable.Find(id);
db.relatedtable.RemoveAll(categoryDetail);
db.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.