如何在Entity Framework中配置事务?

时间:2011-03-26 12:05:53

标签: entity-framework-4 entity-framework-4.1

如何在Entity Framework 4中配置事务?在普通的旧Ado.Net中,我们有一个名为SqlTransaction的类,我们也可以为该事务指定隔离级别,如Read_Committed,Read_UnCommitted等。我在Entity Framework中找不到所有这些选项。我们如何配置它们?

1 个答案:

答案 0 :(得分: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(); 
    }
}