简体   繁体   中英

Delete record that has a foreign key

I'm having issues with my DELETE, If a record has a FK the record won't delete, I have tried to implement a Soft delete approach by adding a bit IsDeleted column and setting the rules.. but that also is in vain.. here is my code

// DELETE: api/ProductCategory/5
[Authorize]
[ResponseType(typeof(Product_Category))]
public async Task<IHttpActionResult> Delete_Product_Category(int id)
{
    Product_Category Product_Category = await db.Product_Category.FindAsync(id);

    if (CRM_Product_Category == null)
    {
        return NotFound();
    }

    db.Product_Category.Remove(Product_Category);
    await db.SaveChangesAsync();

    return Ok(Product_Category);
}

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        db.Dispose();
    }
    base.Dispose(disposing);
}

private bool Product_CategoryExists(int id)
{
    return db.Product_Category.Count(e => e.ProductCategoryID == id) > 0;
}

It's normal, you are trying to delete a category , but how the DB is supposed to handle products linked to that specific category ?

You have 2 choices here :

1 - Checking if you have products linked to the category and delete them or change the category.

2 - Deleting on cascade. (It will delete your linked records on cascade BE CAREFULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM