如何检查现有记录字段并在更改前与发布数据进行比较?

时间:2014-07-16 13:15:59

标签: c# asp.net entity-framework asp.net-mvc-4

我对MVC很新,希望有人能帮助我。

我有一个控制器方法来保存表单中的回发数据。它有一个名为OrderStatus的字段。如果订单状态值为“已接收”,那么我只想执行一段代码。

我在这段代码中所做的是,阅读帖子值并使用Find再次读取EF数据并比较值。一切似乎都没问题但是当我尝试保存记录时,它会给我以下错误。

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

我确实理解了这个问题但是如何检查数据库中的现有值并进行比较和保存。

我的代码在

下面
    // POST: /Purchasing/Edit/5

    [HttpPost]
    public ActionResult Edit(PurchaseMaster purchasemaster)
    {
        if (ModelState.IsValid)
        {
            if (purchasemaster.OrderStatus == "Received")
            {
                string myId = purchasemaster.PurchaseId;
                //check if the existing status is already set as Received or not
                PurchaseMaster pm = db.PurchaseMasters.Find(myId);

                if (pm.OrderStatus != "Received") //this will prevent duplicate stock updates
                {
                    //load the items and loop through to update the stock
                    List<PurchaseDetail> purchasedetails = db.PurchaseDetails.Where(x => x.PurchaseId == myId).ToList();
                    foreach (PurchaseDetail singleitem in purchasedetails)
                    {
                        string itemcode = singleitem.ItemCode;
                        Item item = db.Items.Find(itemcode);
                        item.QtyInHand = item.QtyInHand + singleitem.Quantity;
                        db.Entry(item).State = EntityState.Modified;
                        db.SaveChanges();

                    }
                }
            }

            db.Entry(purchasemaster).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(purchasemaster);
    }

1 个答案:

答案 0 :(得分:1)

试试这个应该有效

//don't get this object from database 
//PurchaseMaster pm = db.PurchaseMasters.Find(myId); 

if (db.PurchaseMasters.Any(x  =>x.Id == myId && x.OrderStatus != "Received") {
   // Do your stuff
}