我有一个简单的WPF网格,它使用Entity Framework从数据库加载数据,我需要允许用户编辑网格中的数据并保存对数据库的更新。
不幸的是,当我尝试通过调用SaveChangesAsync()来保存更新时,我得到以下异常:
System.Data.Entity.Core.OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
调用是在我的一个ViewModel类中进行的:
...
List<Adjustment> changesList = [ here I load the current content of the GridControl ]
MyDbProxy dataProxy = new MyDbProxy();
await dataProxy.SaveAdjustments(changesList);
并且包装DB的类非常简单:
public class MyDbProxy {
private readonly MyDb _db;
public MyDbProxy() {
_db = new MyDb();
}
...
public async Task SaveAdjustments(IEnumerable<Adjustment> changesList) {
using (_db) {
foreach (var a in changesList) {
_db.Adjustments.Attach(a);
_db.Entry(a).State = EntityState.Modified;
}
await _db.SaveChangesAsync();
}
}
}
答案 0 :(得分:0)
抛出此异常是因为您创建了一个新对象,并告诉EF使用EntityState.Modified对其进行了修改