使用ASP.NET Core 1.0 Identity UserManager进行的事务 [英] Transactions with ASP.NET Core 1.0 Identity UserManager

查看:150
本文介绍了使用ASP.NET Core 1.0 Identity UserManager进行的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个应用程序中,除了在UserStore中创建新用户外,我还重写了Asp Core Identity UserManager的CreateAsync-在单独的统计信息表中(在不同的dbcontext上)创建新行.问题是,我希望将这两个操作都在事务内触发,这样,如果一个操作失败-另一个则不提交.这是代码:

In one of my apps, I'm rewriting Asp Core Identity UserManager's CreateAsync, to in addition to creating new user in UserStore - create a new row in a separate statistics table (on a different dbcontext). Problem is, I would like both of those operations to be fired inside a transaction, so that if one fails - the other does not commit. Here's the code :

public override async Task<IdentityResult> CreateAsync(TUser user, string password)
    {
        // We need to use transactions here.            
            var result = await base.CreateAsync(user, password);

            if (result.Succeeded)
            {
                var appUser = user as IdentityUser;

                if (appUser != null)
                {
                    // create user stats.
                    var userStats = new UserStats()
                    {
                        ActionsCount = 0,
                        EventsCount = 0,
                        FollowersCount = 0,
                        ProjectsCount = 0,
                        UserId = appUser.Id
                    };

                    _ctx.UserStats.Add(userStats);
                    await _ctx.SaveChangesAsync();
                }
            }    
            return result;
    }

问题是,我不知道如何设置这样的事务,因为似乎TransactionScope还不是.Net Core的一部分(?),并且正在使用HttpContext.GetOwinContext()为base.CreateAsync()获取当前范围的DbContext. )不起作用,因为HttpContext似乎缺少此方法(在其他一些堆栈溢出答案中暗示无法引用Microsoft.Owin.Host.SystemWeb或Microsoft.AspNet.WebApi.Owin-两者均与.netcore不兼容) .有帮助吗?

Thing is, I have no idea how to set up such a transaction, as it seems TransactionScope is not a part of .Net Core yet (?) and getting currently scoped DbContext for base.CreateAsync() with HttpContext.GetOwinContext() does not work as HttpContext seems to be missing this method (referencing Microsoft.Owin.Host.SystemWeb or Microsoft.AspNet.WebApi.Owin as hinted in some other stack overflow answers won't do - both are not compatible with .netcore). Any help ?

推荐答案

首先,您需要设置正在使用的dbcontext,其标识具有一定范围的生存期:

Firstly you need to setup the dbcontext you are using with identity with a scoped lifetime:

        services.AddDbContext<MyDbContext>(ServiceLifetime.Scoped); // this is the important bit

        services.AddIdentity<User, Role>(options =>
        {
        })
        .AddEntityFrameworkStores<MyDbContext, int>()
        .AddDefaultTokenProviders();

然后,当您需要创建事务时,请执行以下操作:

Then when you need to create a transaction you do the following:

        using (var transaction = await _myDbContext.Database.BeginTransactionAsync())
        {
            var result = await _userManager.CreateAsync(newUser, password);

            try
            {
                if (result.Succeeded)
                {
                    DBItem newItem = new DBItem();
                    _myDbContext.Add(newItem);

                    await _myDbContext.SaveChangesAsync();
                    transaction.Commit();
                }
            }
            catch (Exception e)
            {
                transaction.Rollback();
            }
        }

这篇关于使用ASP.NET Core 1.0 Identity UserManager进行的事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆