2011-03-26 66 views
4

如何在實體框架4中配置事務?在普通的Ado.Net中,我們有一個名爲SqlTransaction的類,我們也可以指定該事務的隔離級別,如Read_Committed,Read_UnCommitted等。我在Entity Framework中找不到所有這些選項。我們如何配置它們?如何在Entity Framework中配置事務?

回答

6

可以使用TransactionScope類,並設置使用TransactionOptions隔離級別描述here

一些的TransactionScope的重載構造接受類型TransactionOptions的結構來指定隔離級別,除一個超時值。默認情況下,事務執行的隔離級別設置爲Serializable。選擇不同於Serializable的隔離級別通常用於讀取密集型系統。這需要對事務處理理論和事務本身的語​​義,所涉及的併發問題以及對系統一致性的影響有深入的瞭解。

例如:

using (var context = new EFTestEntities()) 
{ 
    context.AddToProducts(new Product { Name = "Widget" }); 
    context.AddToProducts(new Product { Name = "Chotchky" }); 

    TransactionOptions options = new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, Timeout = TransactionManager.DefaultTimeout }; 

    using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options)) 
    { 
     // do any EF work that you want to be performed in the transaction 
     context.SaveChanges(); 

     // commit the transaction 
     scope.Complete(); 
    } 
} 
相關問題