我正在为我的新项目使用 Entity Framework 7 或核心 1.0。在产品表中,ProductName 列被设置为备用键(唯一约束)。问题是我无法更新数据库中的这一列。编辑 Action 代码如下:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(ProductViewModel product, int id, IFormFile ProductImage)
{
try
{
if (ModelState.IsValid)
{
var Product = _products.Find(x => x.ProductID == id).Single();
string tempName = Product.ProductName; //for deleting directory if name has been changed.
Product = _mapper.Map<Product>(product);
//code to replace image file if new file has been uploaded OR
//delete / change directory if the product name has been changed
//goes here
//Insert id again after mapping
Product.ProductID = id;
ProductImage image = _images.Find(m => m.ProductID == id).Single();
image.Hash = FileName;
image.Product = Product;
image.Extension = FileExtension;
image.ProductID = Product.ProductID;
_products.Update(Product);
_images.Update(image);
if (_products.SaveAll() && _images.SaveAll())
{
return RedirectToAction("Index");
}
}
}
catch (Exception ex)
{
_logger.LogDebug(ex.Message);
throw;
}
product.Categories = _categories.GetAll().ToList();
return View(product);
}
我已经调试了所有这些并且一切正常,所有其他属性都在数据库中更新,ProductName 正在内存对象(而不是数据库)中更新,文件/文件夹正在被替换,甚至 images 数据库表正在更新,但是当产品名称更改时 SaveAll() if 语句中的 return 语句未执行数据库中的这个特定列也没有被更新。请帮忙!
最佳答案
好的,我已经通过 Entity Framework Core 的 Github 找到了答案。答案如下:
EF Core 当前不支持更改备用键的值。我们有 #4073跟踪虽然删除了此限制。
顺便说一句,如果您希望它用作关系的目标键,它只需要是备用键。如果您只想要一个唯一索引,请使用 HasIndex() 方法,而不是 AlternateKey() 。可以更改唯一索引值。
来源: Github
关于c# - 无法更新备用 key Entity Framework 核心 1.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36200436/