在EF6中,是否可以使用每个调用结构的上下文跨服务调用执行事务?

时间:2015-09-16 12:29:06

标签: c# entity-framework wcf transactions entity-framework-6

我有一个结构设置,对服务器上的WCF服务进行多次服务调用。我有多个DbContexts实例化每次调用。我想将其中一些调用组合到服务器上的单个事务中,同时排除可能同时发生的其他调用。这可能吗?

我的上下文都在单个服务器上的单个应用程序中进行管理,并且所有上下文都使用相同的连接字符串。

我正在寻找像

这样的东西
var transKey = transService.BeginTransaction(); // creates a transaction of some kind.
service1.Execute(transKey); // on the server places the execution within the specified transaction.
service2.Execute(transKey); // same here
transService.CommitTransaction(transKey); // Nothing happens until now (allowing other clients to freely utilize service1 without touching the transaction), the transaction occurs, and everything gets cleaned up.

但是我可能会说错了树。找到这个问题的解决方案的任何帮助都会很有用。

修改

我想要做的是拥有一个跨多个服务调用的指定事务,但不是每个服务调用。我正在寻找一种机制来创建一个事务,然后决定“我想要这个DbContext动作和另一个DbConext动作,但不是这个DbContext动作部分的事务”。然后有权保留该事务,直到我准备好执行它。 TransactionScope我相信不会给我那种控制。

我可能错了,但TransactionScope似乎为每个连接创建一个事务,只要范围处于活动状态,任何和每个DbContext操作都会汇总到事务中。我需要更多地控制进行此类交易的内容。

1 个答案:

答案 0 :(得分:0)

我会使用分布式事务,但使用TransactionInterop.GetTransmitterPropagationToken方法将事务令牌传递给您要参与事务的服务调用。这也意味着您需要修改服务以获取事务ID。另外,在多个appdomains中使用分布式事务时要小心,appdomain必须保持活动状态,直到事务被提交或回滚,否则事务将无法提交。

http://blogs.microsoft.co.il/sasha/2010/04/30/propagating-a-transaction-across-appdomains/

TransactionScope throws TransactionAbortedException when Disposed

http://blogs.msdn.com/b/florinlazar/archive/2008/02/20/flowing-or-propagating-transactions-in-net-blog-entry-under-construction.aspx