2011-06-01 58 views
1

我正在使用ASP.NET MVC 3和實體框架代碼優先。我有一個頁面(使用Razor View Engine),它允許用戶更新模型(產品)的部分:只更新模型的一部分

@ Html.LabelFor(model => model.Overview) @ Html.TextAreaFor(model => model .Overview)

@Html.LabelFor(model => model.Description) 
@Html.TextAreaFor(model => model.Description) 

@Html.HiddenFor(model => model.ProductId) 

我控制器的方法是這樣的:

[HttpPost] 
public ActionResult Update(Product product) 
{ 
    db.Products.Attach(product); 
    db.SaveChanges(); 
} 

所有我想要做的是更新產品型號的概述和說明屬性。但是,當我運行代碼時,模型不會在數據庫中更新,而且也不會出現任何錯誤。當我在調試時檢查產品對象時,我發現雖然ProductId,Overview和Description字段是正確的(按照FORM POST),但其他字段是NULL(我期望)。

我想知道產品對象的不完整狀態是否導致它不保存到數據庫?

這裏是模型:

公共類產品 { 公衆詮釋產品編號{獲得;組; }

[Required(ErrorMessage = "Please enter a description")] 
    [DataType(DataType.MultilineText)] 
    public string Description { get; set; } 

    [DataType(DataType.MultilineText)] 
    public string Overview { get; set; } 

    public int SupplierId { get; set; } 
    public virtual Supplier Supplier { get; set; } 
} 

回答

4

當涉及到編輯,嘗試首先從數據庫中選擇一個現有的記錄(您想編輯的一個),然後從你的表格所收集的值更新(即模型傳遞到您的控制器行動),然後保存它。

E.g.

[HttpPost] 
public ActionResult Update(Product productPassedInFromView) 
{ 
    Product productToEdit = db.Products.Find(productPassedInFromView.ID); 

    productToEdit.Property1 = productPassedInFromView.Property1; 
    productToEdit.Property2 = productPassedInFromView.Property2; 
    //Continue for all the fields you want to edit. 

    db.SaveChanges(); 
} 
-1

如果您知道要更新的實體的哪些屬性,則可以使用EF中的ChangeTracker將僅更改的屬性標記爲已更改。下面是一個修改實例從優秀圖書[編程實體框架:的DbContext(http://shop.oreilly.com/product/0636920022237.do):

db.Products.Attach(product); 
var entry = db.Entry(product); 
entry.State = EntityState.Unchanged; 
entity.Property(p => p.Overview).IsModified = true; 
entity.Property(p => p.Description).IsModified = true; 
db.SaveChanges(); 

這將爲你節省往返到數據庫。但當然,只有當你知道哪些屬性正在改變時它纔有效。還有其他一些方法可以達到這個目的,但這個最直接。