ASP中更新数据库时数据丢失.净MVC



我有一个2值的模型(+ PK) -

public int Id { get; set; }
public string ImageDescription { get; set; }
public byte[] Image { get; set; }

但是当用户更新ImageDescription字段时,图像将从数据库中删除。我正在使用自动生成的控制器进行编辑。

public async Task<IActionResult> Edit(int id, [Bind("Id,ImageDescription")] Gallery gallery)
{
if (id != gallery.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(gallery);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!GalleryExists(gallery.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(gallery);
}

你在Bind中没有Image,只有ImageDescription,这就是为什么你不能保存它

public async Task<IActionResult> Edit(int id, [Bind("Id,ImageDescription")] Gallery gallery)

如果你不想保存新图像,想要保留之前的图像,你可以使用下面的代码

var existedGallery=_context.Set<Gallery>().FirstOrDefault(i=> i.Id==gallery.Id);
if(existedGallery!=null)
{
existedGallery.ImageDescription=gallery.ImageDescription;
_context.Entry(existedGallery).Property(i => i.ImageDescription).IsModified = true;
var result = await _context.SaveChangesAsync();
}

最新更新