0

I want to exchange db.Products.SingleOrDefault(n => n.ProductID == id) by method Delete in class Product_BLL but error "The object cannot be deleted because it was not found in the ObjectStateManager".

This is my code:

public ActionResult Delete(int id)
    {
        if (id.ToString() == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        //public class Product_BLL { 
            //public static Product Delete(int id)
            //{
            //LOLShopEntities db = new LOLShopEntities();
            //var p = db.Products.SingleOrDefault(n => n.ProductID == id);
            //return p;
            //}
        //}
        var p = Product_BLL.Delete(id);

        //var p = db.Products.SingleOrDefault(n => n.ProductID == id);
        if (p == null)
        {
            return HttpNotFound();
        }
        db.Products.Remove(p);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
aybe
  • 15,516
  • 9
  • 57
  • 105
Khanh
  • 1
  • Check that the object exists before deleting it ? – aybe Mar 08 '18 at 16:59
  • but if i use var p = db.Products.SingleOrDefault(n => n.ProductID == id); No error – Khanh Mar 08 '18 at 17:04
  • Yes, because if you look up the object first it's attached to the ObjectStateManager. I'm guessing you need to put `db.Products.Attach(p);` before the line `db.Products.Remove(p);` – Equalsk Mar 08 '18 at 17:09
  • Possible duplicate of [Delete a single record from Entity Framework?](https://stackoverflow.com/questions/17723276/delete-a-single-record-from-entity-framework) – Equalsk Mar 08 '18 at 17:09

0 Answers0