实体框架:控制数据库连接并指定自己的事务 [英] Entity Framework: Controlling db connection and specifying own transaction

查看:102
本文介绍了实体框架:控制数据库连接并指定自己的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种方法来控制EF的基础数据库连接&事务以确保我的应用程序在一次事务期间一次仅使用一个连接(我需要同时支持Oracle和SQL Server。)。

I want to find a way to control EF's underlying db connection & transaction to make sure my application is using only one connection at a time during one transaction (I will need to support both Oracle and SQL Server).

我发现此好文章,其中包含很多建议,但会提出 TransactionScope (就像我阅读的所有其他文章一样)。好吧,如果可能的话,我想远离 TransactionScope ...

I found this good article which comes with a lot of recommendations, but brings up (like all the other articles I have read) the TransactionScope. Well, I would like to stay away of TransactionScope, if possible...

我可以为仅使用纯 DbConnection & DbTransaction 还是根本不可能或错误?

Could I have a solution for this playing with only pure DbConnection & DbTransaction or this is simply impossible or wrong?

甚至,我发现本文此处,在以下部分说明:

Even more, I found this article here, stating at section :


指定您自己的交易

"Specifying Your Own Transaction"

就像您可以使用连接覆盖默认行为,
也可以控制交易功能。如果您显式地创建
自己的事务,则SaveChanges将不会创建DbTransaction。不过,您
不会创建System.Common.DbTransaction。相反,当
创建自己的交易时,您需要使用
System.Transaction.TransactionScope对象。

Just as you can override the default behavior with connections, you can also control transaction functionality. If you explicitly create your own transaction, SaveChanges will not create a DbTransaction. You won't create a System.Common.DbTransaction, though. Instead, when creating your own transactions, you need to use a System.Transaction.TransactionScope object.

但是没有任何解释...

But there is no explaination...

我正在使用Entity Framework 5.0。您能帮助我理解以便为我的应用选择正确的吗?

I am using Entity Framework 5.0. Could you please help me understand in order to choose correct for my application? It would be ideal to show me some good patterns of usage.

预先感谢!

注意:我正计划这样做是因为事务升级到了Oracle数据提供者的DTC。

Note: I am planning this because of the transactions escalating to DTC for Oracle Data Provider.

推荐答案

实体框架6有两个功能可能对此有帮助:

Entity Framework 6 has two features which may help with this:

如果您确实想使用EF5,则需要使用TransactionScope:

If you did want to use EF5, you'd need to use a TransactionScope:

var context = new MyContext();

using (var transaction = new TransactionScope())
{
    MyItem item = new MyItem();
    context.Items.Add(item);
    context.SaveChanges();

    item.Name = "Edited name";
    context.SaveChanges();

    transaction.Complete();
}

如链接文章中所述,您将需要引用System.Transactions来获取 TransactionScope

As mentioned in the linked article, you will need to reference System.Transactions to get TransactionScope.

这篇关于实体框架:控制数据库连接并指定自己的事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆