2016-12-29 37 views
-1

我有一個簡單的MVC 5應用程序,在我的控制器中,我想知道如何在調用db.SaveChanges()之前從數據庫訪問當前數據。我有以下代碼:如何在ASP.NET MVC中更新舊實體值

// 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(); 
} 

如果我做product.title它獲取新的價值,我想之前保存訪問舊的價值。

我嘗試了以下鏈接中的接受答案:How to access old entity value in ASP.NET Entity Framework但它不適用於我。

回答

0

你可以這樣做:

// 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(); 
} 
相關問題