簡體   English   中英

創建或更新項目是否存在

[英]Create or update if item exist

我有一個創建表格,如果存在特定的Medicine ,其供應量將更新或添加新的條目,但是如果不存在特定的Medicine ,它將創建新的一批數據。

我在了解更新如何在MVC中工作時遇到了麻煩。

這是錯誤:

存儲更新,插入或刪除語句影響了意外的行數(0)。 自加載實體以來,實體可能已被修改或刪除。

這是我的控制器:

public ActionResult Create([Bind(Include = "SupplyID,MedicineID,Expiration,NumberOfSupply")] Supply supply)
    {
        if (ModelState.IsValid)
        {
            bool supplyExsist = db.Supplies.Any(x => x.Expiration == supply.Expiration && x.MedicineID == supply.MedicineID);

            if (supplyExsist)
            {
                var currentSupply = (from x in db.Supplies //get current supply
                                     where x.MedicineID == supply.MedicineID
                                     && x.Expiration == supply.Expiration
                                     select x.NumberOfSupply).First();

                db.Entry(supply).State = EntityState.Modified;
                supply.NumberOfSupply = currentSupply + supply.NumberOfSupply;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                db.Supplies.Add(supply);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

        ViewBag.MedicineID = new SelectList(db.Medicines, "MedicineID", "MedicineName", supply.MedicineID);
        return View(supply);
    }

模型:

public class Supply
{
    [Key]
    public int SupplyID { get; set; }

    [ForeignKey("Medicine")]
    public int MedicineID { get; set; }
    public Medicine Medicine { get; set; }

    [DataType(DataType.Date)]
    public DateTime Expiration { get; set; }

    [Display(Name = "Quantity")]
    [Range(1, int.MaxValue, ErrorMessage = "The value must be greater than 0")]
    public int NumberOfSupply { get; set; }
}

試試這個

db.Supplies.AddOrUpdate(h => h.medicineID,supply));

它將檢查db中是否存在具有相同葯品ID的行,否則將添加新的行,並對其進行更新

您應該使用以下命令更改if塊:

if (supplyExsist)
            {
                var currentSupply = (from x in db.Supplies //get current supply
                                     where x.MedicineID == supply.MedicineID
                                     && x.Expiration == supply.Expiration
                                     select x.NumberOfSupply).First();

                db.Supplies.Attach(supply);
                db.Entry(supply).State = EntityState.Modified;
                supply.NumberOfSupply = currentSupply + supply.NumberOfSupply;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM