asp.net-identity交易问题
发布时间:2021-03-30 22:10:58 所属栏目: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; } } 希望这可以帮助. (编辑:百色站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-web-api – 在ASP.NET Web API控制器的nunit测试中
- asp.net – IIS 404自定义错误不能按预期工作
- ASP.NET UpdatePanel和Javascript __dopostback
- asp.net-mvc-3 – 具有最佳实践的示例N层ASP.NET MVC3应用程
- 何时在ASP.NET上选择LAMP?
- .net – RESTful WCF的裸最低配置
- asp.net-mvc-4 – 在EF迁移配置类的Seed方法中获取App_Data
- asp.net-mvc – 从ASP.NET Web API返回一些字段
- asp.net-mvc – 如何在视图上下文之外获取ModelMetadata?
- asp.net – 错误:数据绑定方法(如Eval(),XPath()和Bind()只
推荐文章
站长推荐
热点阅读