【EFCore】EF Core事务提交,分布式事务

EFCore 专栏收录该内容
6 篇文章 1 订阅

EF Core的SaveChanges方法本身就是事务

 

但是如果多个SaveChanges方法提交,则需用IDbContextTransaction

using (EFCoreContext context = new EFCoreContext())
{
    IDbContextTransaction tran = null;
    try
    {
        tran = context.Database.BeginTransaction();
        context.UserInfo.Add(new UserInfo()
        {
            Name = "haha11",
            Age = 19
        });
        context.SaveChanges();

        context.UserInfo.Add(new UserInfo()
        {
            Name = "haha22",
            Age = 19
        });
        context.SaveChanges();

        tran.Commit();
    }
    catch (Exception ex)
    {
        if (tran != null)
            tran.Rollback();

        Console.WriteLine(ex.Message);
    }
    finally
    {
        tran.Dispose();
    }

}

 

如果是多个Context,即分布式事务,则需用TransactionScope

using (EFCoreMigrationContext context1 = new EFCoreMigrationContext())
using (EFCoreMigrationContext context2 = new EFCoreMigrationContext())
{
    using (TransactionScope transactionScope = new TransactionScope())
    {
        try
        {
            context1.UserInfo.Add(new UserInfo()
            {
                Name = "hehe11",
                Age = 20
            });
            context1.SaveChanges();

            context2.UserInfo.Add(new UserInfo()
            {
                Name = "hehe22",
                Age = 20
            });
            context2.SaveChanges();

            transactionScope.Complete();

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

 

  • 2
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值