2

I have a standard MVC application using the out-of-the-box code generated with the scaffolding for application functionality (CRUD). I'm trying to evaluate whether a particular field has been changed in order to accomplish additional tasks on my data. Apparently my idea of how OriginalValues and CurrentValues isn't the way it is actually implemented (ugh!). Any ideas on how to compare the values to make this happen? Thanks in advance...

    [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);
    }
RobRichard
  • 100
  • 3
  • 11

1 Answers1

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.... 
    }

You can look into each entity entry in the ChangeTracker and check the EntityState. Your st1 and st2 value comparisons should then return the values you wanted to compare.

Aaroninus
  • 1,062
  • 2
  • 17
  • 35
Mike Ramsey
  • 843
  • 8
  • 23
  • Hmm... Implemented this code, but when it hits the foreach loop, there are no items found even though changes were indeed made. – RobRichard Jun 20 '12 at 21:07
  • Possible related issue about ChangeTracker. http://stackoverflow.com/a/5810010/925808 – Mike Ramsey Jun 20 '12 at 22:15
  • Crap! Looks like I'm going to have to go old school and store the original value in a hidden field, and then compare the two... – RobRichard Jun 20 '12 at 23:38