Delete the foreign key data when the data in the foreign table is deleted

ado.net-entity-data-model asp.net-mvc entity-framework-6 linq linq-to-entities

Question

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.

enter image description here (the error I get)

How to do/fix that? (help me make the right title)

1
1
7/7/2016 1:27:24 PM

Accepted Answer

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.

1
7/8/2016 12:58:56 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow