MVC .Net Cascade Deleting when using EF Code First Approach

后端 未结 2 1337
情歌与酒
情歌与酒 2021-02-14 06:10

I\'m pretty new to MVC and i\'m having troubles with cascade deleting. For my model I the following 2 classes:

    public class Blog
    {
        [Key]
                 


        
2条回答
  •  我寻月下人不归
    2021-02-14 06:32

    Not sure what you are trying to do here, but you have one record so not sure why you are trying to loop. Here is my delete code:

    public ActionResult Delete(int id)
    {
        try {
            Products products = context.Products.Single(x => x.productId == id);
            return View(products);
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
            CompileAndSendError(ex);
            return View(new Products());
        }
    }
    
    //
    // POST: /Products/Delete/5
    
    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        try {
            Products products = context.Products.Single(x => x.productId == id);
            context.Products.Remove(products);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("",ex.Message);
            CompileAndSendError(ex);
            return RedirectToAction("Index");
        }
    }
    

提交回复
热议问题