我有一个示例应用程序来演示Linq错误Row not found or changed
数据库记录如下所示 -
从我的申请表中,我想更新位置从“伦敦”到“巴黎”的员工。这是我的代码 -
var dbContext = new EmployeeDataContext();
var employeesInLondon = from emp in dbContext.Employees
where emp.Location.Equals("London")
select emp;
foreach (var employeeInLondon in employeesInLondon)
{
employeeInLondon.Location = "Paris";
}
//Simulate as if another user is updating the database before you submit the update
Console.WriteLine("Now update the Employee table by running this in SQL Server Management Studio:");
Console.WriteLine("UPDATE Employee SET Location = 'Delhi', LastName = 'John' WHERE Location = 'London';");
Console.WriteLine("And hit any key...");
Console.ReadKey();
dbContext.Refresh(RefreshMode.KeepChanges); //Why the error is thrown even after adding this statement
dbContext.SubmitChanges();
正如您在上面的代码中看到的那样 - 在提交更改之前,我通过SSMS运行不同的Update SQL。并且错误按预期抛出。
所以,我在调用SubmitChanges()
-
dbContext.Refresh(RefreshMode.KeepChanges);
我的问题是,即使我在调用SubmitChanges()
之前刷新数据库上下文,仍然会抛出错误。我仍然使用上面的代码获得ChangeConflictException。
请指导我在这里缺少什么?
FYI, 我使用下面的链接来创建上面的演示,我知道如何添加catch块来列出冲突的对象/成员 - Row not found or changed - Finding the culprit
答案 0 :(得分:2)
如果存在冲突异常,您需要解决它...即使您在保留修改时刷新,但在提交更改时仍然存在未解决的冲突。
如果您更新它(因此没有冲突),则刷新上下文将会执行,而不是保留更改。
如果您想保留更改,请尝试执行以下操作:
try
{
// the parameter tells it go ahead and update all non-conflicting items
// afterwards it'll throw having all conflicting items stored
dbContext.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException ex)
{
foreach (ObjectChangeConflict o in dbContext.ChangeConflicts)
o.Resolve(RefreshMode.KeepChanges); // Resolve the conflicts, not just
// refresh the context
dbContext.SubmitChanges(); // and submit again
}