MVC3与EF 4.1和EntityState.Modified更新

Bar*_*cha 5 .net entity-framework asp.net-mvc-3

在使用.NET MVC3更新对象时,我在理解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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

尝试编辑并随后更新此对象时出现问题.这是我的编辑操作.

    [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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我认为问题来自于我正在设置EntityState.Modified,它将所有属性标记为已修改.如果我没有上传新图像,那么来自前端的ImageFilePath和ImageContentType实际上是null,这是存储的内容.

我的问题是如何解决这个问题?使用EntityState.Modified的正确方法是什么?

小智 0

在提交时,您需要检查模型是否有效,然后运行 ​​CRUD 例程。

if(ModelState.IsValid)
{
   // Save my model
}
Run Code Online (Sandbox Code Playgroud)