2011-10-06 43 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太棒了! –