我在嘗試更新用戶。與ASP.NET身份用戶管理器的交易
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 context是否會被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;
}
謝謝!我的第一個想法是直接使用支持事務的dbContext操作AspNetUsers表,但我認爲這是不可能的。我認爲必須使用UserManager來更新身份系統中的用戶,是否沒有其他方法? – nmit026
是的,你可以通過'dbContext'直接操作用戶記錄。這就是'AppUserManager'所做的事情,只是增加了一些驗證 – trailmax
你是Owin和Identity的專家,也許你可以看看這個:http://stackoverflow.com/questions/43037450/usermanager-updateuser-method- isnt線程安全 – nmit026