我正在尝试更新用户。
MyClass
如果后续调用Web API失败,我需要回滚对用户的任何更改。我知道交易,比如:
AppUserManager appUserManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
AppUser member = await appUserManager.FindByIdAsync(User.Identity.GetUserId());
member.HasScheduledChanges = true;
IdentityResult identityResult = appUserManager.Update(member);
但是在try块中使用AppUserManager进行的操作是否是事务性的?另外,他们使用相同的EFDbContext实例吗?换句话说,我不知道第二个代码示例开头的var context是否会被try块中的appUserManager“Update”方法调用使用。
此外,AppUserManager的创建方式如下:
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.
}
}
}
答案 0 :(得分:7)
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;
}
}
答案 1 :(得分:4)
使用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进行交易。但它工作我,如果在事务中发生任何错误,它将回滚所有事务。