2011-01-30 10 views
4

私は2つの独立した(関係のない)エンティティを持っています。これらのプロパティの一部が変更され、SaveChangesが呼び出されます。彼らは私のアプリケーションの状態をポーズするので、私は両方の更新を1つのトランザクションにラップする必要があります。EF4トランザクションで2つの更新をラップする方法

SQLプロファイラのように2つの更新が実行されます。しかし、私はどんな取引も見ることができません。 なぜEF4は2つのアップデートの周りにトランザクションを作成しませんか?それをどうすれば実現できますか? (私はすでにトランザクションスコープを試しましたが、プロファイラで見られるトランザクションはまだありません)

どのようなアイデアですか?

+1

を変更するのTransactionScopeがこれを解決します。接続文字列にEnlist = falseのようなものが含まれていないことを確認してください。 –

答えて

2

これは機能するはずですが、正しい順序で処理する必要があります。ここで

は、いくつかのsudoのコードです:

using (TransactionScope scope = new TransactionScope()) 
{ 
    //Do something with context1 
    //Do something with context2 

    //Save Changes but don't discard yet 
    context1.SaveChanges(false); 

    //Save Changes but don't discard yet 
    context2.SaveChanges(false); 

    //if we get here things are looking good. 
    scope.Complete(); 

    //If we get here it is save to accept all changes. 
    context1.AcceptAllChanges(); 
    context2.AcceptAllChanges(); 

} 

あなたはまだ問題があなたのコードを投稿している場合。

+0

SaveChanges(false)の理由は何ですか?私は、それ以降のAcceptAllChanges()なしでSaveChanges(true)だけで十分であるはずだと思います。エラーが発生すると例外が発生し、scope.Complete()は呼び出されません。 –

+0

トランザクションが失敗し、save changes = trueを使用すると、メモリー内に変更のリストがありません。この方法では、メモリ内の変更を失う前に、すべてのデータをディスクに保存します。 –

+0

ああ、それを得た - 説明のおかげで。 –

1

私の記録が保存されますちょっと私はいけない場合でも、wirteはすべて受け入れる

using (TransactionScope scope = new TransactionScope()) 
{ 
    Roll rsr = new Roll(); 
    rsr.RoleName = "krians"; 
    studentEntities.Rolls.AddObject(rsr); 

    Roll rsssddr = new Roll(); 
    rsssddr.RoleName = "kriansss"; 
    studentEntities1.Rolls.AddObject(rsssddr); 

    //Do something with context1 
    //Do something with context2 
    var sdfsf = studentEntities.ObjectStateManager; 

    //Save Changes but don't discard yet 
    studentEntities.SaveChanges(false); 

    var sdfssdfdsff = studentEntities.ObjectStateManager; 
    var sdsdfdsffsf = studentEntities1.ObjectStateManager; 

    //Save Changes but don't discard yet 
    studentEntities1.SaveChanges(false); 

    var sdsdfdsffsasdfasdff = studentEntities1.ObjectStateManager; 

    //if we get here things are looking good. 
    scope.Complete(); 

    var sdfsf3 = studentEntities.ObjectStateManager; 
    var sdfsfasdfasdf3 = studentEntities1.ObjectStateManager; 
    //If we get here it is save to accept all changes. 
    //studentEntities.AcceptAllChanges(); 
    //studentEntities1.AcceptAllChanges(); 
} 
関連する問題