gpt4 book ai didi

asp.net-identity - 交易/Database.BeginTransaction 和 IdentityManager

转载 作者:行者123 更新时间:2023-12-01 01:04:52 25 4
gpt4 key购买 nike

我有一个复杂的添加过程来创建用户(并将角色 + 其他用户相关信息添加到其他表)

有谁知道在添加用户/角色或其他身份对象时如何使用事务。我似乎无法访问“Database.BeginTransaction”

我有以下 UserManager 类,我不确定如何访问基类“商店”

public class UserManager : UserManager<ApplicationUser>
{
public UserManager()
: base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
{
//allows alphanumeric names in username
UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
}

}

似乎没有办法访问 UserManager.UserStore.Database ...

谢谢

最佳答案

ASP.NET Identity 框架的当前存储实现使用 EntityFramework。 DbContext 是 EF 的核心,其中 TransactionScope 可用于保存多个更改。

下面是 EF Code First DBContext and Transactions 的一个例子

using(var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
// Do something like Add a User
context.SaveChanges();
// Do something like Add a User to Role
context.SaveChanges();

scope.Complete();
}

更新 1:
- 要访问 DbContext.Database 使用 IdentityManager.Store.Context.Database- 您可以使用相同的 ConnectionString(不是 SqlConnection 对象)跨多个 DbContext 使用相同的方法

此外,查看下一个链接以了解 BeginTransaction 的用法。 -> How do you configure the Transaction time out in Entity Framework 6 DbContext.Database.BeginTransaction?

更新 2:

使用 EF6 BeginTransaction : Working with Transactions (EF6 Onwards)

使用以下代码伪
ApplicationDbContext ctx = new ApplicationDbContext();
using (DbContextTransaction tran1 = ctx.Database.BeginTransaction())
{
using (MyDbContext ctx2 = new MyDbContext(ctx.Database.Connection, false))
{
ctx2.Database.UseTransaction(tran1.UnderlyingTransaction);
}
}

来自 Working with Transactions (EF6 Onwards)

Note: The contextOwnsConnection flag must be set to false when called in this scenario. This is important as it informs Entity Framework that it should not close the connection when it is done with it

关于asp.net-identity - 交易/Database.BeginTransaction 和 IdentityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19657667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com