I’m reading Pro ASP.NET MVC 3 Framework by Apress. I’m following the example of uploading and displaying images. The problem is that it works fine when uploading images to products, but if I later want to edit the description for example and then saving the product the image disappears. I understand that the problem is that when saving the product I’m not passing the image data because the image upload is empty, and the context.SaveChanges() saves every data field, including the empty image data fields.
I’m stuck and I would really appreciate if someone could help me!
This is a part of the edit page:
<label>Image</label>
if (Model.ImageData == null)
{
@:Null
}
else
{
<img id="imageFile" runat="server" src="@Url.Action("GetImage", "Product", new { Model.Name })" />
}
<label>Upload image:</label>
<input type="file" name="Image" runat="server" />
When updating:
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
repository.SaveProduct(product);
TempData["message"] = string.Format("{0} har sparats", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
}
Saving the product:
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
else
{
context.Entry(product).State = EntityState.Modified;
}
int result = context.SaveChanges();
}
Your understanding of the problem is correct: when you mark your
ProductasEntityState.ModifiedEF marks all of its properties modified. So when your currentProductis coming from the controller and it doesn’t have an image EF removes it from the DB when callingSaveChanges().I see two options:
You load the original
Productand just update the needed properties instread of usingEntityState.Modified:In this case you have to manually set every property on the
Product.After you have marked your
Productas Modified you re-set the image values from the db:I this case you only need to re-set the image related properties.
With both implementation there is no way to remove the ImageData during update.