避免 EF 将空图像更新到 .Net MVC 中的数据库

Avoid EF update the null image to database in .Net MVC

在我的SachController中,有一个如下所示的编辑方法。在视图中,有几个 textbox 和一个 file-input 用于上传 image 对象。有时,用户不想更改图像,他们只是不想 select 新图像。 image (HttpPostedFileBase) 为空。

如何避免空图像但仍然使用像这样的短更新:

            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit([Bind(Include = "MaSach,NhanDe,MaDM,MaNXB,NamXB,GiaBia,PhanTramGiamGia,TrongLuong,MaBV,MaBia,Dai,Rong,Cao")] Sach sach, HttpPostedFileBase image)
            {
                if (ModelState.IsValid)
                {
                    uploadImage(sach, image);
                    db.Entry(sach).State = EntityState.Modified;                
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.MaBV = new SelectList(db.BaiViet, "MaBV", "NhanDe", sach.MaBV);
                ViewBag.MaBia = new SelectList(db.Bia, "MaBia", "TenBia", sach.MaBia);
                ViewBag.MaNXB = new SelectList(db.NhaXuatBan, "MaNXB", "Ten", sach.MaNXB);
                return View(sach);
            }

将图像 属性 标记为未修改:

db.Entry(sach).State = EntityState.Modified;
if (image == null)
   db.Entry(sach).Property(m => m.Image).IsModified = false;
db.SaveChanges();