asp.net-identity交易问题
发布时间:2021-03-31 03:06:32 所属栏目: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;
}
}
希望这可以帮助. (编辑:岳阳站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- IIS和ASP.Net Web开发服务器之间的行为差异?
- asp.net文件上传示例分享
- asp.net-core – 如何在Visual Studio 2015 RC中为ASP.NET
- Asp.Net GridView删除Html样式
- asp.net-mvc – 如何在asp.net mvc中处理分页?
- ASP.NET中下载文件的几种实例代码
- asp.net-mvc – 使用输出缓存和其他动作过滤器
- asp.net-mvc – 使用AWS .NET SDK进行SNS订阅确认示例
- asp.net-mvc – 如何使用ASP.NET MVC ApiController获取GET
- asp.net-core – ClaimTypes的ASP.NET要求
推荐文章
站长推荐
热点阅读
