我有一个小型演示应用程序来处理存储在数据库中的二进制数据。相关代码见下:
实体类:
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Display(Name = "Full Name:")]
public string Name { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Photo:")]
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
编辑动作:
[HttpGet]
public ActionResult Edit(int id)
{
var mensPlayer = _dataSource.MensPlayers.FirstOrDefault(p => p.Id == id);
return View(mensPlayer);
}
[HttpPost]
public ActionResult Edit(MensPlayer mensPlayer, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
//Added line below
_dataSource.ImageTemp(mensPlayerInDb, mensPlayer);
if (image != null)
{
mensPlayer.ImageMimeType = image.ContentType;
mensPlayer.ImageData = new byte[image.ContentLength];
image.InputStream.Read(mensPlayer.ImageData, 0, image.ContentLength);
}
//Added line below
mensPlayer.ImageData = mensPlayerInDb.ImageData;
//Save Player
_dataSource.Update(mensPlayer);
_dataSource.Save();
TempData["message"] = string.Format("{0} has been saved", mensPlayer.Name);
return RedirectToAction("Detail", "MensPlayer", new {id = mensPlayer.Id});
}
return View(mensPlayer);
}
获取图像方法:
public FileContentResult GetImage(int id)
{
var image = _dataSource.MensPlayers.FirstOrDefault(p => p.Id == id);
if (image != null)
{
return File(image.ImageData, image.ImageMimeType);
}
return null;
}
显示图像:
@if (Model.ImageData != null) {
<div >
<img width="300" height="400" src="@Url.Action("GetImage", "MensPlayer",
new { Model.Id })" alt="Player Image"/>
</div>
}
数据源类
public interface IDataSource
{
IQueryable<MensTeam> MensTeams { get; }
IQueryable<MensPlayer> MensPlayers { get; }
IQueryable<MensHome> MensHomes { get; }
void Save();
void Update(MensPlayer mensPlayer);
void Delete();
void ImageTemp(MensPlayer mensPlayerInDb, MensPlayer mensPlayer);//I added this
}
在 Db 类中
void IDataSource.Save()
{
SaveChanges();
}
void IDataSource.Update(MensPlayer mensPlayer)
{
Entry(mensPlayer).State = EntityState.Modified;
}
//Added code below
void IDataSource.ImageTemp(MensPlayer mensPlayerInDb, MensPlayer mensPlayer)
{
Entry(mensPlayerInDb).CurrentValues.SetValues(mensPlayer);
}
我的问题是,每次我尝试编辑播放器时,都会从数据库中很好地检索每个数据,但是当我在编辑后点击保存时,ImageData 会丢失,更像是用空值替换原始数据。就像,应用程序希望我在每次尝试编辑时重新上传图像。
我能做些什么来清理这个?