asp.net-identity交易问题
发布时间:2021-03-30 17:02:34 所属栏目: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下文件上传和文件删除的代码
- asp.net-mvc – ASP.NET MVC 3 Treeview
- asp.net-mvc – asp.net mvc – string或int的路由(即/ typ
- asp.net – Visual Studio – 为什么.ASPX文件比.ASPX.CS文
- asp.net-mvc-3 – 大量使用ViewBag
- asp.net – 选择框更改事件中的setTimeout
- asp.net – 如何从Javascript调用控制器方法
- asp.net-mvc-3 – “字段宽度必须是数字.”在客户端
- WPF中ComboBox绑定数据库自动读取产生数据
- asp.net – 绑定ListView InsertItemTemplate中的DropDownL
推荐文章
站长推荐
热点阅读
