asp.net-identity交易问题
发布时间:2021-03-30 21:45:19 所属栏目: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; } } 希望这可以帮助. (编辑:4S站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – (客户端)禁用提交按钮的最佳方法是什么?
- asp.net-mvc-4 – 在哪里可以找到WebMatrix.WebData.WebSec
- asp.net-mvc – 通过Gitignore递归地包含Nuget DLL
- asp.net – 请求URL在IIS 7中无效
- asp.net-mvc – 我如何moq aingleingleResult?我是不是该?
- 如何在ASP.NET 5中添加一个TypeScript绝对类型的定义?
- asp.net-mvc – MVC应用程序中的随机数生成
- asp.net – 如何使用javascript生成假回发?
- asp.net-mvc-3 – 应该使用HTTP引用来验证还是令牌验证来防
- asp.net – 如何序列化LINQ-to-SQL惰性列表
推荐文章
站长推荐
- asp.net – FormsAuthentication.GetRedirectUrl
- asp.net-mvc – Nhibernate / MVC:在View中处理
- asp.net – MVC 3,(razor)加载部分与验证
- asp.net fileupload控件上传文件与多文件上传
- asp.net-mvc – 使用MVC3剃刀的ASP.Net图表控件
- asp.net – 从我的GridView行返回一个对象
- asp.net – 如何从WCF客户端拦截raw soap reques
- ASP.NET自带对象JSON字符串与实体类的转换
- 从app_data中删除文件夹时如何防止asp.net重新编
- asp.net-mvc – 将DropDownListFor绑定到字典
热点阅读