gpt4 book ai didi

.net - MVC3 与 EF 4.1 和 EntityState.Modified 更新

转载 作者:行者123 更新时间:2023-12-04 20:53:23 24 4
gpt4 key购买 nike

在使用 .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 的正确方法是什么?

最佳答案

您可以从数据库中检索模型并使用 UpdateModel 获取新值(如果存在),而不是通过在参数中接受 SneakPeakCollection 来使用隐式模型绑定(bind)。像这样的东西:

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();

关于.net - MVC3 与 EF 4.1 和 EntityState.Modified 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7677133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com