如何在实体框架中配置事务?

发布于 2024-10-27 18:43:29 字数 154 浏览 2 评论 0原文

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

How do I configure transactions in Entity Framework 4? In plain old Ado.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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆梦 2024-11-03 18:43:29

您可以使用 TransactionScope 类,并设置隔离使用 TransactionOptions 的级别,如此处

TransactionScope 的一些重载构造函数接受 TransactionOptions 类型的结构来指定隔离级别以及超时值。默认情况下,事务执行时隔离级别设置为可序列化。选择 Serialized 以外的隔离级别通常用于读密集型系统。这需要对事务处理理论和事务本身的语​​义、涉及的并发问题以及对系统一致性的影响有深入的了解。

例如:

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

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(); 
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文