2011-10-02 68 views
0

我是.NET MVC(Learning)的新手。我在控制器下面的方法(這是不乾淨的代碼和我學習)如何在實體框架中手動更新模型

 [HttpPost] 
     public ActionResult Edit(ProductCategoryLocation viewModel) 
     { 
      if (ModelState.IsValid) 
      { 
       var product = viewModel.Product; 
       product.Category = db.Categories 
        .Where(c => c.ID == viewModel.CategoryID).Single();         
       db.Entry(product).State = EntityState.Modified;    
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      return View(viewModel); 
     } 

視圖模型擁有產品,位置和類別類型和類別ID和LocationID。在POST方法中,我從View Model中獲取類別ID,更新產品的類別,然後將模型更新到數據庫。除手動更改的類別外,對產品屬性的任何更改都會保存。

有沒有錯誤/我錯過了什麼? 這是使用View Model進行更新的正確方法嗎?

回答

0

您可以直接將視圖模型的CategoryID分配給產品的CategoryID。這樣您就不必從數據庫中檢索類別。

[HttpPost] 
    public ActionResult Edit(ProductCategoryLocation viewModel) 
    { 
     if (ModelState.IsValid) 
     { 
      var product = viewModel.Product; 
      product.CategoryID = viewModel.CategoryID;         
      db.Entry(product).State = EntityState.Modified;    
      db.SaveChanges(); 

      return RedirectToAction("Index"); 
     } 

     return View(viewModel); 
    } 

如果沒有一個標量屬性CatagoryID你在Product

public class Product 
{ 
    public int ID { get; set; } 

    //other properties 

    public int CategoryID { get; set; } 
    public virtual Category Category { get; set; } 
} 
+0

感謝定義它。產品類已經有類別。我可以使用「Product.Category.ID = viewModel.CategotyID」來分配類別嗎? – RAM

+0

@RAM這是行不通的。您需要在'Product'類中指定'CategoryID'。 – Eranga

+0

嗨Eranga ..謝謝我會測試這個。 – RAM