加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:25:32 所属栏目:asp.Net 来源:网络整理
导读:在使用.NET MVC3更新对象时,我在理解EntityState.Modified方面遇到了问题. 我有一个模型,可以在上传图像时存储ImageFilePath和ImageContentType.这是创建动作的样子. [HttpPost] public ActionResult Create(SneakPeekCollection collection,HttpPostedFileB
在使用.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的正确方法是什么?

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读