Search code examples
c#asp.net-mvcentity-frameworkupdatemodel

Store update, insert, or delete statement affected an unexpected number of rows (0),


Hope you are doing well.

Kindly help me to resolve this.I am using below code in ASP.NET mvc web Application.

[HttpPost]
        public ActionResult ProductAddonsAdd(int? id, tblproductattributemapper model, string AllStorechk, int? ddlProduct, int? ddlCompany, string hdCompanyProductID)
        {

            DbTransaction dbTran = null;
            try
            {
                tblproductattributemapper tblattributValMapper = new tblproductattributemapper();
                db.Connection.Open();
                dbTran = db.Connection.BeginTransaction();
                int CompanyProductID = 0;
                if(!string.IsNullOrEmpty(hdCompanyProductID))
                {
                    CompanyProductID=Convert.ToInt32(hdCompanyProductID);
                }
                else
                {CompanyProductID=db.tblcompanyproducts.Where(x => x.nProductID == ddlProduct && x.nCompanyID == ddlCompany).FirstOrDefault().nCompanyProductID;}
                if (id == null)
                {
                    if (db.tblproductattributemappers.Where(x => x.nCompanyProductID == CompanyProductID && x.nAttributeID == model.nAttributeID).Count() != 0)
                    {
                        TempData["Errmsg"] = "Addon value already exist with this product!";
                        return RedirectToAction("ProductAddons");
                    }

                    tblattributValMapper = new tblproductattributemapper();
                    tblattributValMapper.nAttributeID = model.nAttributeID;
                    tblattributValMapper.nCompanyProductID = CompanyProductID;
                    db.AddTotblproductattributemappers(tblattributValMapper);
                }
                else
                {
                    tblattributValMapper = db.tblproductattributemappers.Where(x => x.nMapperID == id).FirstOrDefault();
                    tblattributValMapper.nAttributeID = model.nAttributeID;
                    tblattributValMapper.nCompanyProductID = CompanyProductID;

                }

                db.SaveChanges();    //// Error comes here when it goes into else part(update mode) then executed here
                // deleting objects
                var objmapperdetails = db.tblproductattributemapperdetails.Where(x => x.nMapperID == tblattributValMapper.nMapperID).ToList();
                if (objmapperdetails != null && objmapperdetails.Count() > 0)
                {
                    foreach (var item in objmapperdetails)
                    {
                        db.tblproductattributemapperdetails.DeleteObject(item);
                    }
                }
                string[] arrAllStore = AllStorechk.Split(',');
                tblproductattributemapperdetail detail;
                foreach (var item in arrAllStore)
                {
                    Int64 _id = Convert.ToInt64(item);
                    detail = new tblproductattributemapperdetail();
                    detail.nMapperID = tblattributValMapper.nMapperID;
                    detail.nAttributeValueMasterID = _id;
                    detail.nPrice = db.tblattributevaluemasters.Where(x => x.nAttributeValueMasterID == _id).FirstOrDefault().nPrice;
                    db.AddTotblproductattributemapperdetails(detail);
                }

                db.SaveChanges();
                dbTran.Commit();
                TempData["Successmsg"] = "Saved successfully";
            }
            catch (Exception ex)
            {
                dbTran.Rollback();
                TempData["Errmsg"] = "Failed to save ";
                Common.TrapError(ex.StackTrace, "Attribute/ProductAddons");
            }
            finally
            {
                db.Connection.Close();
            }
            return RedirectToAction("ProductAddons");
        }

When I open any record in edit mode and submit without changing any thing; at that time it goes to else part and update the entity tblattributValMapper properities nAttributeID & nCompanyProductID with older values, when db.SaveChanges(); got executed it thorwing 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."

I check it on google and applied some solution like db.Refresh(RefreshMode.ClientWins,tblattributValMapper );

but it doesn't help me.

I am single developer working on this project so entity is not updating from any other place,I also check the Primary Key value,it is passing through model. Can any one have any Idea where I am doing mistake. Please see the attached screen shots.

Any help would much appreciated.


Solution

  • I fixed the problem by using below code. it work for me in update mode.

      try
      { db.SaveChanges(); }
      catch (OptimisticConcurrencyException)
      {
      db.Refresh(RefreshMode.StoreWins, tblattributValMapper);
      db.SaveChanges();
      }
    

    Thanks.