2011-06-06 12 views
3

我已經調用Membership API和角色API在相同的事務範圍。我讀過打開多個連接導致升級需要啓用分佈式事務,所以我正在尋找一種方法來打開一個連接並與之共享:成員資格,角色,我自己的調用。TransactionScope與成員資格和角色調用在同一個塊(只使用一個連接的方式?)

這裏是工作的代碼,導致不必要的升級:

public static void InsertUser(string userName, string email, string roleName, int contactId, string comment) 
     { 
     /* 
      * Exceptions thrown here are caught in the DetailView's event handler and piped to the UI. 
      */ 

     using(var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew)) 
     { 
      string password = Membership.GeneratePassword(Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters); 
      const string passwordQuestion = "Should you change your password question?"; 
      const string passwordAnswer = "yes"; 
      MembershipCreateStatus status; 
      MembershipUser user = Membership.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, true, out status); 

      if(user == null) 
      { 
       throw new Exception(GetErrorMessage(status)); 
      } 

      // Flesh out new user 
      user.Comment = comment; 
      Membership.UpdateUser(user); 

      // Give user a role 
      Roles.AddUserToRole(user.UserName, roleName); 

      // Create bridge table record 
      Guid userId = (Guid)ExceptionUtils.ThrowIfDefaultValue(user.ProviderUserKey, "ProviderUserkey is null!"); 
      insertIntoAspnet_Users_To_Contact(userId, contactId); 

      // Send welcome email 
      EmailUtils.SendWelcomeEmailFromAdmin(userName, email, password, passwordQuestion, passwordAnswer, roleName); 

      transactionScope.Complete(); 
     } 
     } 

感謝

+0

是否將您的數據庫連接設置爲池?如果是這樣,底層連接將保持打開幾秒鐘,看看你是否會提出額外的請求。如果是,即使使用新的連接對象,它也會使用相同的連接。這一切都歸結爲我相信的連接池。 – 2011-06-06 20:55:37

回答

2

如果你有SQL2008或更高,它可以處理多個連接的交易,沒有升級到MSDTC。要求是您爲所有連接使用完全相同的連接字符串。

如果你在一個較低的SQL服務器版本,我認爲你鬆動。我在幾個月前調查了這個,發現沒有辦法處理它,所以我最終跳過了事務並實現了自己的錯誤處理。客戶擁有SQL2005並且無法升級。

0

您指定TransactionScopeOption.RequiresNew,這意味着每次你在這段代碼打發時間,你一個新的事務,即使已經有一個合適的環境。

只是這樣做:

using(var transactionScope = new TransactionScope()) 
+0

從我讀過的內容來看,它有多個打開的連接導致需要啓用MSDTC的升級。在任何情況下,使用空構造函數都不幸解決了這個問題。 – 2011-06-06 20:29:32

相關問題