entity-framework-4 – 如何在Entity Framework中配置事务?

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

Some of the overloaded constructors of TransactionScope accept a structure of type TransactionOptions to specify an isolation level, in addition to a timeout value. By default, the transaction executes with isolation level set to Serializable. Selecting an isolation level other than Serializable is commonly used for read-intensive systems. This requires a solid understanding of transaction processing theory and the semantics of the transaction itself, the concurrency issues involved, and the consequences for system consistency.

例如:

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(); 
    }
}
相关文章
相关标签/搜索