2016-03-21 5 views
0

LINQのエラーにRow not found or changedデータベースのコンテキスト - 更新(RefreshMode.KeepChanges);

データベースのレコードをデモするサンプルアプリケーションは、次のようになり、私がしている -

enter image description here

私のアプリケーションから、私は「パリ」に「ロンドン」から場所を持つ従業員を更新します。

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によって異なる更新SQLを実行し、ちょうど私の変更を提出する前に、ここに私のコードです。期待どおりにエラーがスローされます。

だから、私はちょうどSubmitChanges()を呼び出す前に、コードの下に追加 -

dbContext.Refresh(RefreshMode.KeepChanges); 

エラーはまだ私はSubmitChanges()を呼び出す前に、データベースコンテキストを更新してもスローされ、なぜ私の質問です。私はまだ上記のコードでChangeConflictExceptionを取得しています。

ここで私が紛失しているものを教えてください。 FYI

、 は、私はデモの上に作成するためのリンクの下に使用していると私は矛盾するオブジェクト/メンバーを一覧表示するcatchブロックを追加する方法を知っている - Row not found or changed - Finding the culprit

+0

これはエンティティフレームワークではありません@Eldho、これはLINQからSQLへの(あなたの再タグ付け程度)であります – Jcl

答えて

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 
} 
関連する問題