4

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

4

1 回答 1

6

您可以使用TransactionScope类,并使用TransactionOptions设置隔离级别,如下所述:

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(); 
    }
}
于 2011-03-26T12:56:25.620 回答