【发布时间】:2011-12-02 09:23:06
【问题描述】:
在使用 .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();
}
}
在尝试编辑并随后更新此对象时出现问题。这是我的编辑操作。
[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 的正确方法是什么?
【问题讨论】:
-
您的问题解决了吗?你用了什么解决方案?请告诉我。
标签: .net asp.net-mvc-3 entity-framework