I have 2 database tables, and I want when I delete a data in the table where the foreign key is pointing (where the primary key is), the foreign key pointing to that data also be deleted.
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Report report = await db.Reports
.Include(i => i.RepFilters)
.Where(i => i.ID == id).SingleAsync();
db.Reports.Remove(report);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
The foreign key is not nullable.
How to do/fix that? (help me make the right title)
It can be possible when .Net or EF generated the code for your context that the
.WillCascadeOnDelete()
was set to false, so just change it to true and try if it works.
If you don't want to do it through the SQL server, you'll have to load all the child objects in the db context
and delete them.