开发者

How do I configure transactions in Entity Framework?

How do I configure transactions in Entity Framework 4? In plain old A开发者_运维知识库do.Net we had a class named SqlTransaction, we could also specify isolation level for that transaction like Read_Committed, Read_UnCommitted etc. I can't find all these options in Entity Framework. How can we configure them?


You can use the TransactionScope class, and set the isolation level using TransactionOptions as described 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.

For example:

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(); 
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜