我正在尝试创建分层 MVC 项目,但我在 EF 中遇到更新问题。我收到以下错误。
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.
我有 DAL 和 BusinessLayer。在 DAL 中,我有以下更新代码
public void Update(params T[] entities)
{
using (var context = new BorselDBEntities())
{
foreach (T entity in entities)
{
context.Entry(entity).State = EntityState.Modified;
}
context.SaveChanges();
}
}
这就是我从 BusinessLayer 调用 DAL 的方式
public void UpdateProduct(params Product[] products)
{
_productRepository.Update(products);
}
为什么会出现上述错误,我该如何解决?
最佳答案
一个常见的原因是 context.Entry(entity) 无法获取您要更新的实体。
调试时,查看 context.Entry(entity) 是否返回实体;通过将其放在单独的行上并在之后设置断点可以轻松完成:
public void Update(params T[] entities)
{
using (var context = new BorselDBEntities())
{
foreach (T entity in entities)
{
var myEntity = context.Entry(entity);
myEntity.State = EntityState.Modified;
}
context.SaveChanges();
}
}
如果不是,您将需要重新检查您的代码并弄清楚为什么它无法接收它。这通常是因为身份/主键列未在“实体”上设置。
例如在 MVC 应用程序中,如果您有一个编辑/更新表单,请记住有一个
@Html.HiddenFor(model => model.Id)
关于c# - EF,更新不起作用,它表示自加载实体以来实体可能已被修改或删除。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43501428/