我正在尝试更新一个用户。
AppUserManager appUserManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
AppUser member = await appUserManager.FindByIdAsync(User.Identity.GetUserId());
member.HasScheduledChanges = true;
IdentityResult identityResult = appUserManager.Update(member);
如果对Web API的后续调用失败,我需要回滚对用户的任何更改。我知道交易,比如:
using (var context = HttpContext.GetOwinContext().Get<EFDbContext>())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
// Changes
member.HasScheduledChanges = true;
// Would this be transactional?
IdentityResult identityResult = appUserManager.Update(member);
context.SaveChanges();
dbContextTransaction.Commit();
}
catch //(Exception ex)
{
// dbContextTransaction.Rollback(); no need to call this manually.
}
}
}
但是,在try块中使用AppUserManager执行的操作会是事务性的吗?此外,它们是否使用EFDbContext的相同实例?换句话说,我不知道第二个代码示例开头的var上下文是否会被try块中的appUserManager"Update"方法调用所使用。
此外,AppUserManager是这样创建的:
public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
EFDbContext db = context.Get<EFDbContext>();
AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));
// etc.
return manager;
}
EFDbContext
是相同的-在这两种情况下,都是从OWIN上下文中解决的,所以这不是问题。然而,Identity是以存储不可知的方式编写的,这意味着存储机制可以被非SQL Server所取代。这就要求AppUserManager
内部缺少事务。所以你需要创建自己的。
我经常在我的生产应用程序中使用var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)
(只使用更多的体系结构):
using(var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
AppUserManager appUserManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
AppUser member = await appUserManager.FindByIdAsync(User.Identity.GetUserId());
member.HasScheduledChanges = true;
IdentityResult identityResult = appUserManager.Update(member);
scope.Complete();
}
catch (Exception ex)
{
scope.Dispose();
throw;
}
}
使用asp.net标识UserManager 的事务提交/回滚的完整解决方案
var appDbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
using (var identitydbContextTransaction = appDbContext.Database.BeginTransaction())
{
try
{
var result = await UserManager.CreateAsync(user, "password");
if (result.Succeeded)
{
var userinfo = await UserManager.FindByNameAsync("Email");
var userId = user.Id;
await UserManager.AddToRoleAsync(userId, "rolename");
identitydbContextTransaction.Commit();
}
}
catch (Exception)
{
identitydbContextTransaction.Rollback();
}
}
它可能会帮助您使用asp.net身份UserManager进行交易。但它对我有效,如果事务中发生任何错误,它将回滚所有事务。