src/EasyFrameWork/RepositoryPattern/Transaction.cs

(完整代码) 1KB

/* http://www.zkea.net/ 
 * Copyright (c) ZKEASOFT. All rights reserved. 
 * http://www.zkea.net/licenses */

using Easy.RepositoryPattern;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Easy.RepositoryPattern
{
    public class Transaction : IDisposable
    {
        private readonly IDbContextTransaction _transation = null;
        public Transaction(params DbContext[] dbContexts)
        {
            for (int i = 0; i < dbContexts.Length; i++)
            {
                if (i == 0)
                {
                    _transation = dbContexts[i].Database.BeginTransaction();
                }
                else
                {
                    dbContexts[i].Database.UseTransaction(_transation.GetDbTransaction());
                }
            }
        }
        public Action Invoke { get; set; }
        public void Dispose()
        {
            try
            {
                if (Invoke == null) throw new Exception("Please set Transaction.Invoke!");
                Invoke?.Invoke();
                _transation.Commit();
            }
            catch
            {
                _transation.Rollback();
                throw;
            }
            finally
            {
                _transation.Dispose();
            }
        }
    }
}

24 小时内免费解锁 3 个项目,之后 1 算力/个。 规则说明

AI 解读 AI

登录后可用,每次 10 算力,解读结果公开显示在下面。

还没有人解读过这个文件。