在Asp.Net Core中为IdentityDbContext和ApplicationDbContext创建公共事务

时间:2019-06-06 14:40:50

标签: c# asp.net-core asp.net-identity-2

我的IdentityDbContext具有以下用户和角色。

public class IdentityDbContext : IdentityDbContext<AdditionalIdentityUser, AdditionalApplicationRole, Guid>
{
    public IdentityDbContext(DbContextOptions<IdentityDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);            
    }
}

我有用于其他表的ApplicationDbContext。

public partial class ApplicationDbContext : DbContext
{
    public ApplicationDbContext()
    {
    }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Table1> Table1 { get; set; }
    public virtual DbSet<Table2> Table2 { get; set; }
}

我有创建用户代码,在其中我使用IdentityDbContext创建用户和角色记录,并使用Application Dbcontext进行其他一些更新。我想在一次交易中做到这一点。

我有:

 public async Task<IActionResult> Create(CreateModel model)
{
    //context here is the context injected through dependency injection.
     using (var appdbContextTransaction = context.Database.BeginTransaction())
     {
         try
         {        

            //Creating using identity Context
            var user = await userManager.CreateAsync(model.User);

           //Random code which uses ApplicationDbContext
            var updateCount = context.Table1.Update();
            appdbContextTransaction .Commit();
        }
        catch (Exception ex)
        {
            appdbContextTransaction.Rollback();
        }
}

但是在例外情况下,只有appdbcontext值会更改,而不是使用标识创建的值。如何创建可以涵盖两种情况的全面交易?

编辑:This问题似乎很相似,但答案无济于事。

0 个答案:

没有答案