0

I have table called "Categories"
enter image description here

Which has a relationship with this table

enter image description here

How can I for a example delete the "ForumTest" category and all the threads related to it in the second table?

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");
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Thenis
  • 61
  • 1
  • 10

2 Answers2

1

You need to config your relationship with cascading delete. Override OnModelCreating method in your context and add this:

modelBuilder
    .Entity<Thread>()
    .HasRequired(s => s.Category)
    .WithMany(r => r.Threads)
    .HasForeignKey(s=>s.CategoryId)
    .WillCascadeOnDelete(true);
ocuenca
  • 38,548
  • 11
  • 89
  • 102
0
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();
DBB
  • 137
  • 1
  • 4