4

ユーザーを作成するための複雑な追加プロセスがあります(そして、ロールと他のユーザー関連情報を他のテーブルに追加します)

ユーザー/ロールまたは他のアイデンティティオブジェクトを追加するときにトランザクションを使用する方法を知っている人はいますか? 「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 にアクセスする手段がないようです...

ありがとう

4

1 に答える 1

4

ASP.NET Identity フレームワークの現在のストレージ実装では、EntityFramework が使用されます。DbContext は、TransactionScope を使用して複数の変更を保存できる EF の心臓部です。

以下は、EF Code First DBContext と 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 の使用方法については、次のリンクを参照してください。-> Entity Framework 6 DbContext.Database.BeginTransaction でトランザクション タイムアウトをどのように構成しますか?

更新 2:

EF6 BeginTransaction の使用:トランザクションの操作 (EF6 以降)

次のコード疑似を使用する

ApplicationDbContext ctx = new ApplicationDbContext();
using (DbContextTransaction tran1 = ctx.Database.BeginTransaction())
{
    using (MyDbContext ctx2 = new MyDbContext(ctx.Database.Connection, false))
    {
        ctx2.Database.UseTransaction(tran1.UnderlyingTransaction);
    }
}

トランザクションの操作 (EF6 以降)から

注: このシナリオで呼び出すときは、contextOwnsConnection フラグを false に設定する必要があります。これは、接続が完了したときに接続を閉じてはならないことを Entity Framework に通知するため、重要です。

于 2013-10-29T12:24:42.293 に答える