【问题标题】:asp.net-identity transaction issueasp.net-identity 交易问题
【发布时间】:2015-02-06 06:31:34
【问题描述】:

我想在同一个事务中创建一个具有角色的用户,但我的实现有问题。为了在事务中使用 userStore 并且让它不自动保存更改并忽略我的事务,我不得不关闭 AutoSaveChanges。这使得它会等到我调用保存更改。这很好用,但是因为当我调用 manager.Create 时用户存储现在不返回 userId,因为它关闭了,所以我没有要传递给 userManager.AddToRole 的 ID。有什么方法可以将我尝试创建的用户添加到同一事务中的角色?

【问题讨论】:

    标签: asp.net transactions asp.net-identity


    【解决方案1】:

    如果您手动启动事务,然后提交它,则在事务中写入数据库的所有内容都将保存在您的事务中。如果你愿意,你可以回滚它。

    做这样的事情:

    var dbContext = // get instance of your ApplicationDbContext
    var userManager = // get instance of your ApplicationUserManager
    using (var transaction = dbContext.Database.BeginTransaction(IsolationLevel.ReadCommitted))
    {
        try
        {
            var user = // crate your ApplicationUser
            var userCreateResult = await userManger.CreateAsync(user, password);
            if(!userCreateResult.Succeeded)
            {
                // list of errors in userCreateResult.Errors
                transaction.Rollback();
                return userCreateResult.Errors;
            }
            // new Guid for user now saved to user.Id property
            var userId = user.Id;
    
            var addToRoleresult = await userManager.AddToRoleAsync(user.Id, "My Role Name");
            if(!addToRoleresult.Succeeded)
            {
                // deal with errors
                transaction.Rollback();
                return addToRoleresult.Errors;
            }
    
            // if we got here, everything worked fine, commit transaction
            transaction.Commit();
        }
        catch (Exception exception)
        {
            transaction.Rollback();
            // log your exception
            throw;
        }
    }
    

    希望这会有所帮助。

    【讨论】:

    • 如果 dbContext 与用于创建 ApplicationUserManager 实例的上下文不同怎么办?这还能用吗?
    • @nmit026 理论上事务是数据库级别的操作,所以它应该与两个dbContexts一起工作,但我从未尝试过。可能上面创建的事务是连接级事务;并且两个 dbContext 将有两个不同的连接,因此在此基础上可能无法正常工作。对于您的情况,也许应该以不同的方式开始交易:using(TransactionScope tran = new TransactionScope()) { // do work; tran.Complete(); } 在此处查看更多信息:stackoverflow.com/a/224702/809357
    • @nmit026 请记住,Identity 在所有地方都使用async,因此需要在创建事务范围时牢记这一点:var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)
    • 谢谢!或许你可以看看我今天问的这个问题:stackoverflow.com/questions/36636272/…
    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    • 2012-01-23
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多