我一直在关注 Apress Pro ASP.NET MVC 3 Framework 书中的 SportsStore 示例项目,并尝试将这些概念应用到我的应用程序中。困扰我的一个地方是,在示例中,我可以将图像添加到产品中并将其保存到数据库中,但是如果我编辑任何给定产品,而不为其上传新图像,则图像数据将被清除。我希望能够编辑产品,但如果从 HTTP post 返回的图像数据为空,我希望 Entity Framework 保留现有的图像数据(和内容类型)。如果未上传新图像,如何命令 EF 不将此图像字段更新为 null?
以下是 SportsStore 示例中的编辑代码:
[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if(image != null)
{
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} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
}
编辑:对于 Rondel - 这是产品类的定义
namespace SportsStore.Domain.Entities
{
public class Product
{
[HiddenInput(DisplayValue=false)]
public int ProductId { get; set; }
[Required(ErrorMessage = "Please enter a product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Please specify a category")]
public string Category { get; set; }
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
}
}
编辑如何让 EF 仅保存某些字段,而使数据库中的其他字段保持不变?
最佳答案
这里的基本问题是,当您将 Product
保存回数据库时,您将使用任何内容覆盖 ImageMimeType
和 ImageData
字段MVC3 使用 FormCollection
中的值填充该 Product
。现在,您需要检查 image==null
是否存在,但您没有实现重用旧 Product
图像信息的逻辑。这是您想要执行的操作:
if (ModelState.IsValid)
{
if(image != null)
{
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
else
{
//set this Product image details from the existing product in the db
product.ImageMimeType= getImageMimeTypeForProduct(product.ProductId );
product.ImageData = getImageDataForProduct(product.ProductId );
}
_repository.SaveProduct(product);
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
显然这两种方法并不真正存在,但想法是相同的。您希望从数据库中获取该产品的现有值,并确保这些值反射(reflect)在 Product
的本地版本中,然后再保存并覆盖这些值。
关于asp.net-mvc - MVC - 如果图像未在 HTTP post 中重新上传,则不保存空图像数据(来自 SportsStore 示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8649287/