MVC3 with EF 4.1 and EntityState.Modified on upgrade

I have trouble understanding EntityState.Modified when it comes to updating an object using .NET MVC3.

I have a model that stores ImageFilePath and ImageContentType when loading an image. Here's what the create action looks like.

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

The problem occurs when you try to edit and subsequently update this object. This is my edit action.

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

I believe the problem is that I am setting up EntityState.Modified, which marks all properties as changed. If I do not upload a new image, ImageFilePath and ImageContentType coming from the front-end are actually null, which is what is stored.

My question is: how can I solve this? What is the correct way to use EntityState.Modified?

+5
3

, SneakPeakCollection , db UpdateModel , . - :

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

, , CRUD.

if(ModelState.IsValid)
{
   // Save my model
}
0

All Articles