asp.net-identity交易问题

tha*_*gan 5 asp.net transactions asp.net-identity

我想在同一个事务中创建一个具有角色的用户,但我对实现有一个问题.为了在事务中使用userStore并让它不自动保存更改并忽略我的事务,我必须关闭AutoSaveChanges.这使它等到我调用保存更改.这工作正常,但因为当我调用manager.Create时,用户现在不会返回userId,因为这是关闭我没有ID传递到userManager.AddToRole.有没有办法将我想要创建的用户添加到同一事务中的角色?

tra*_*max 3

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

做这样的事情:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。