Search code examples
c#asp.net-mvc-3entity-framework-4.1

Having problems while updation in asp.net mvc project


My create and delete operations are working well. But, the Edit function is giving the following error :- Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

NOTE:- CatPicView is a ViewModel merging the two entities Category and Picture

Following is the code for my Edit action code :-

[HttpPost]
public ActionResult Edit(CatPicView catPic)
{
    if (ModelState.IsValid)
    {
        if (!String.IsNullOrEmpty(catPic.Picture.PictureUrl))
        {
            if (catPic.Category.PictureId == null)
            {
                Picture picture = new Picture();
                picture.PictureUrl = catPic.Picture.PictureUrl;
                db.Pictures.Add(picture);
                catPic.Category.PictureId = picture.Id;
            }
            else
            {
                db.Entry(catPic.Picture).State = EntityState.Modified;
            }
        }
        db.Entry(catPic.Category).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.ParentCategoryId = new SelectList(db.Categories, "Id", "Name", catPic.Category.ParentCategoryId);
    return View(catPic);
}

Solution

  • Using the debuger, check the properties of the object you are trying to update. The most likely is that you have an ID in null.

    To fix this, you should place a hidden field holding the id of the modified object so when posting the form it became mapped to your object.