Carl
Carl

Reputation: 817

How to get old entity value on update in ASP.NET MVC

I have a simple MVC 5 Application, In my controller I want to know how I can access the current data from database before the db.SaveChanges() is called. I have the following code:

// GET:
public ActionResult Edit(int id)
{
    Product product = db.Products.Find(id);
    return View(product);
}

// POST:
[HttpPost]
public ActionResult Edit([Bind(Include = "id,title,content,price)] Product product)
{
    /* How to access old value from database here? */

    db.Entry(product).State = EntityState.Modified;
    db.SaveChanges();
}

If I do product.title it is retrieving the new value, I want to access the old value before the save.

I tried the accepted answer in this link: How to access old entity value in ASP.NET Entity Framework but it didn't work for me.

Upvotes: 0

Views: 3254

Answers (1)

Carl
Carl

Reputation: 817

You can do:

// POST:
[HttpPost]
public ActionResult Edit([Bind(Include = "id,title,content,price)] Product product)
{
    var original_data = db.Products.AsNoTracking().Where(P => P.id == product.id).FirstOrDefault();

    /* Use original_data.title here */

    db.Entry(product).State = EntityState.Modified;
    db.SaveChanges();
}

Upvotes: 2

Related Questions