c# - TransactionScope 在同一 block 中调用 Membership 和 Roles(仅使用一个连接的方式?)

标签 c# membership roles transactionscope

我在同一事务范围内调用了成员资格 API 和角色 API。我读到打开多个连接会导致需要启用分布式事务的升级,因此我正在寻找一种方法来打开一个连接并将其共享给:成员资格、角色、我自己的调用。

这是导致意外升级的工作代码:

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

谢谢

最佳答案

如果您有 SQL2008 或更高版本,它可以处理跨多个连接的事务,而无需升级到 MSDTC。要求是您对所有连接使用完全相同的连接字符串。

如果您使用的是较低的 SQL 服务器版本,我认为您已经松了。几个月前我对此进行了调查,但发现没有办法处理它,所以我最终跳过了事务并改为实现了我自己的错误处理。客户有 SQL2005,无法升级。

关于c# - TransactionScope 在同一 block 中调用 Membership 和 Roles(仅使用一个连接的方式?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6257383/

相关文章:

c# - Visual Studio 不断为 Strings.resx 生成多个 Strings#.Designer.cs 文件

c# - Nancy.Authentication.Token - token 以奇怪的间隔过期?

c# - 如何查看DbContext是否有事务?

ASP.NET 标识

php - 建立基于 Paypal 的成员(member)网站 - total noob - would appreciate help

postgresql - 如何使用 Odoo 从两个不同的 PostgreSQL 角色登录同一个数据库?

c# - 不可变类型的实例如何本质上是线程安全的

asp.net-mvc - 每个区域成员的 ASP.Net MVC

python - Discord.py 如何从 DM 检查某个服务器中的用户拥有哪些角色?

spring - 如何在Spring Security 3中设置用户角色?