2011-10-26 7 views
0

(注:私はthisを参照してください、それは私がやりたい正確に何ではありません。)EF4 - トランザクション内でアイデンティティを抽出し、後続のSaveChanges()を実行します。デタッチまたは複数のコンテキスト?

私は次の操作を行う必要がある要件があります。

  1. を新しいFooエンティティを作成します
  2. Fooエンティティが作成されると、新しいFooAuditエンティティを作成し、テキスト説明の新しいFooエンティティの新しい識別値を使用します。 FooAuditはFooとの関係がないため、IDはFooの作成から手動で取得する必要があります。
  3. トランザクションをコミットしない場合、EntityStateFooレコード(Added)を保持して、これらの処理をすべて実行するか、またはまったく実行しないでください。

他のコンテキストを使用していますか?

 
using (var fooContext = GetContext()) 
{ 

    fooContext.Foos.AddObject(new Foo()); 

    using (var transaction = new TransactionScope()) 
    { 

     // Save Foo, while maintaining the Changed EntityState until AcceptAllChanges 
     fooContext.SaveChanges(SaveOptions.DetectChangesBeforeSave); 

     using (var auditContext = GetContext()) 
     { 
      // Save FooAudit, maintaining the Changed EntityState until AcceptAllChanges 
      auditContext.FooAudits.AddObject(new FooAudit()); 
      auditContext.SaveChanges(SaveOptions.DetectChangesBeforeSave); 
      transaction.Complete(); 
      fooContext.AcceptAllChanges(); 
      auditContext.AcceptAllChanges(); 
     } 
    } 
} 

もっと良い方法がありますか?

答えて

0

私はこれを図示の別のコンテキストを使用して解決しました。

関連する問題