2011-10-06 44 views
5

我有理解EntityState.Modified當談到更新與.NET MVC3對象的問題。MVC3與EF 4.1和EntityState.Modified上更新

我有當圖像被上載,存儲的ImageFilePath和ImageContentType的典範。這是創建操作的樣子。

[HttpPost] 
    public ActionResult Create(SneakPeekCollection collection, HttpPostedFileBase image) 
    { 
     try 
     { 
      if (image != null) 
      { 
       var filepath = Path.Combine(HttpContext.Server.MapPath("../../Uploads"), Path.GetFileName(image.FileName)); 
       image.SaveAs(filepath); 
       collection.ImageContentType = image.ContentType; 
       collection.ImageFilePath = "~/Uploads/" + image.FileName; 

      } 
      _db.SneakPeekCollections.Add(collection); 
      _db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 

嘗試編輯並隨後更新此對象時出現問題。這是我的編輯操作。

[HttpPost] 
    public ActionResult Edit(int id, SneakPeekCollection collection, HttpPostedFileBase image) 
    { 
     try 
     { 
      if (image != null) 
      { 
       var filepath = Path.Combine(HttpContext.Server.MapPath("../../../Uploads"), Path.GetFileName(image.FileName)); 
       image.SaveAs(filepath); 
       collection.ImageContentType = image.ContentType; 
       collection.ImageFilePath = "~/Uploads/" + image.FileName; 
      } 
      _db.Entry(collection).State = EntityState.Modified; 
      _db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 

我相信這個問題來自於事實,我設置EntityState.Modified改性這標誌着所有屬性。如果我沒有上傳一個新的圖像,來自前端的ImageFilePath和ImageContentType實際上是null,這就是存儲的內容。

我的問題是我該如何解決這個問題?什麼是使用EntityState.Modified的正確方法?

+0

是你的問題解決了嗎?你用什麼解決方案?請告訴我。 –

回答

0

在提交時,您需要檢查模型是否有效,然後運行您的CRUD例程。

if(ModelState.IsValid) 
{ 
    // Save my model 
} 
+0

這不起作用。該對象保存得很好,但正如我所提到的,它清除了ImageFilePath和ImageContentType屬性,因爲它們沒有明確設置並且EntityState.Modified已被調用。 –

+0

您可以請張貼您的SneakPeak類定義嗎? – 2011-10-06 19:26:41

3

而不是使用隱式模型通過在參數接受SneakPeakCollection綁定的,你可以檢索來自數據庫的模型,並使用的UpdateModel如果存在的話,以獲得新的價值。事情是這樣的:

var collection = _db.SneakPeaks.Find(id); // Get the entity to update from the db 
UpdateModel(collection); // Explicitly invoke model binding 
if (image != null) 
{ 
       var filepath = Path.Combine(HttpContext.Server.MapPath("../../../Uploads"), Path.GetFileName(image.FileName)); 
       image.SaveAs(filepath); 
       collection.ImageContentType = image.ContentType; 
       collection.ImageFilePath = "~/Uploads/" + image.FileName; 
} 
_db.SaveChanges(); 
0
+0

嘿Peretz。謝謝。我閱讀了你的鏈接,並且能夠解決我需要在Edit form post中維護CreatedOn值的問題。我做的是,在編輯帖子中,我提取了現有的行,並從這些數據中獲得了CreratedOn的值,並在後期將其設置爲模型對象...是不是?你說的話? –

+0

@RajanRawal太棒了! –