客户端的事务

本文关键字:事务 客户端 | 更新日期: 2023-09-27 18:03:57

我有一个大问题使用或理解使用wsdualhttpbinding WCF事务。

我有这样的东西:

IService:

[ServiceContract]
public interface IService
{
  //...
  [OperationContract]
  [ApplyDataContractResolver]
  [TransactionFlow(TransactionFlowOption.Mandatory)] 
  bool SaveDevice(Device device);
  //...
}

Service.svc.cs:

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
  public class Service : IService
  {
   [OperationBehavior(TransactionScopeRequired = true)]
   public bool SaveDevice(Device device)
   {
            bool temp = false;
            Transaction transaction = Transaction.Current;
            using (EntityConn context = new EntityConn())
            {
                try
                {
                  //....
                }
             }
    }
   }

Model.cs 所以这里我在我的客户端,并尝试执行一个操作与事务需求:

if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                try
                {
                   //do some stuff
                }
            }
          }

我得到一个错误:事务。电流为空

  1. 这条路对吗?
  2. 如果不是,我该如何解决?

谢谢你的帮助

EDIT:我只需要把if放在using

之后
    using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
    {
     if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
     {
            try
            {
               //do some stuff
            }
     }
    }

客户端的事务

在TransactionScope之外,我认为是Transaction。Current将始终为空。您需要首先输入事务范围,然后开始访问transaction . current的属性。看起来您正在尝试在客户端执行一些非事务性操作?如果是,试试这个:

using (TransactionScope tran = new TransactionScope())
{
    if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
    {
        // ambient transaction is not escalated; exclude this operation from the ambient transaction
        using (TransactionScope tran2 = new TransactionScope(TransactionScopeOption.Suppress))
        {
            // do some stuff
        }
    }
    else
    {
        // ambient transaction is escalated
        // do some other stuff
    }
}

注意:我已经复制了示例代码中的条件,但是您应该验证这是正确的测试。根据MSDN,在分布式事务之外,TransactionInformation.DistributedIdentifiernull,而不是Guid.Empty

我认为您想在OperationBehavior属性上添加AutoEnlistTransaction=true。同样,您可能希望添加AutoCompleteTransaction=true。