加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-identity交易问题

发布时间:2020-12-15 19:49:14 所属栏目:asp.Net 来源:网络整理
导读:我想在同一个事务中创建一个具有角色的用户,但我对实现有一个问题.为了在事务中使用userStore并让它不自动保存更改并忽略我的事务,我必须关闭AutoSaveChanges.这使它等到我调用保存更改.这工作正常,但因为当我调用manager.Create时,用户现在不会返回userId,
我想在同一个事务中创建一个具有角色的用户,但我对实现有一个问题.为了在事务中使用userStore并让它不自动保存更改并忽略我的事务,我必须关闭AutoSaveChanges.这使它等到我调用保存更改.这工作正常,但因为当我调用manager.Create时,用户现在不会返回userId,因为这是关闭我没有ID传递到userManager.AddToRole.有没有办法将我想要创建的用户添加到同一事务中的角色?

解决方法

如果您手动启动交易,然后提交,交易中写入数据库的所有内容都将保留在您的交易中.如果你愿意,你可以回滚.

做那样的事情:

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

希望这可以帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读