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

747 views Asked by At

In my SachController, there is an Edit method like below. In the view, there are several textbox and one file-input for upload image object. Sometime, user doesn't want to change the image and they just don't select a new image. And the image (HttpPostedFileBase) is null.

How can I avoid the null image but still use short update like this:

            [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);
            }
1

There are 1 answers

0
Alexander Polyankin On BEST ANSWER

Mark Image property as not modified:

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