2

我有一个标准的 MVC 应用程序,它使用由应用程序功能脚手架 (CRUD) 生成的开箱即用代码。我正在尝试评估特定字段是否已更改,以便对我的数据完成其他任务。显然,我对 OriginalValues 和 CurrentValues 的想法并不是它实际实现的方式(呃!)。关于如何比较这些值以实现这一点的任何想法?提前致谢...

    [HttpPost]
    public ActionResult Edit(Address address)
    {
        if (ModelState.IsValid)
        {
            string st1 = db.Entry(address).Property(p => p.locationTypeId).CurrentValue.ToString();
            //string st2 = db.Entry(address).Property(p => p.locationTypeId).OriginalValue.ToString();

            bool bLocationTypeChanged = false;
            db.Entry(address).State = EntityState.Modified;
            db.SaveChanges();

            // Other stuff happens here

            return RedirectToAction("Index");
        }

        ViewBag.locationTypeId = new SelectList(db.LocationTypes, "locationTypeId", "name", address.locationTypeId);
        return View(address);
    }
4

1 回答 1

1
if (ModelState.IsValid)
{        
    foreach (var entry in db.ChangeTracker.Entries<Address>().Where(a => a.State != EntityState.Unchanged))
    {
        string st1 = entry.Property(p => p.locationTypeId).CurrentValue.ToString();
        string st2 = entry.Property(p => p.locationTypeId).OriginalValue.ToString();

        //Do your extra stuff based on your comparison here.... 
    }

您可以查看 ChangeTracker 中的每个实体条目并检查 EntityState。然后,您的st1st2值比较应该返回您想要比较的值。

于 2012-06-20T15:06:04.040 回答