这笔交易有效吗? ASP.NET 存储库模式

问题描述

谢谢光临。 我是一个新的 C#、ASP .NET 程序员。我正在使用 Postgresql 和 ASP.NET 3.1 来构建一个后端网站。使用存储库模式,它进行得很顺利,然后出现了问题。

当我更新 2 个不同的实体 A 和 B 时。A 工作得很好,但 B 失败了。在正常情况下,应该删除 A 一个。但有些 A 仍然存在于数据库中。

所以我对事务、工作单元、工作单元 + 存储库模式进行了一些研究,...

然后我想出了一些理想,我想知道这是否可行。或者有什么问题、缺点、优点或者这个。

所以这是存储库,

public class BaseRepository<TEntity> where TEntity : class
{
        public readonly GolfdbContext Context;
        public readonly DbSet<TEntity> Entities;

        public BaseRepository(GolfdbContext context)
        {
            Context = context;
            Entities = Context.Set<TEntity>();
        }

        public void Add(TEntity entity)
        {
            Entities.Add(entity);
        }
}

这是交易

public class DatabaseTransaction
{
        protected readonly GolfdbContext Context;
        private IDbContextTransaction transaction;

        public DatabaseTransaction(GolfdbContext context)
        {
            Context = context;
        }

        public async Task<bool> Commit()
        {
            await this.transaction.CommitAsync();
            return true;
        }

        public void BeginTransaction()
        {
            this.transaction = Context.Database.BeginTransaction();
        }

        public async void Rollback()
        {
            await this.transaction.RollbackAsync();
        }
}

这是在启动文件

{
            ....
            services.AddTransient<RepoA>();
            services.AddTransient<RepoB>();

            services.AddTransient<ServiceC>();
            services.AddTransient<DatabaseTransaction>();

            services.AddHttpContextAccessor();

            services.AddDbContext<DbContext>(options =>
                 options.UseNpgsql(
                     Configuration.GetConnectionString("MyWebApiConnection"))
            ));
            ...
}

这是在服务 C

public class ServiceC
{
        private readonly RepoA _repoA;
        private readonly RepoB _repoB;
        private readonly DatabaseTransaction _dbtransaction;
        
        public ServiceC(RepoA repoA,RepoB repoB,DatabaseTransaction dbtransaction)
        {
            _repoA = repoA,_repoB = repoB,_dbtransaction = dbtransaction
        }


        public async void Example(entityA a,entityB b)
        {
             try
             {
                _databaseTransaction.BeginTransaction();
                repoA.Add(a);
                repoB.Add(b);
                await _databaseTransaction.Commit();
             }
             catch (Execption e)
             {
                _databaseTransaction.Rollback();
                throw new Exception("Create Account Error: " + exception);
             }
        }
}

这意味着,我将在函数的第一行设置事务,如果 2 repoA.Add(a) 起作用而 repoB.Add(B) 不起作用,那么我们不能回滚并抛出异常,如果 2 个函数起作用,则 dbcontext 将成为 Commit()SaveChanges()

感谢阅读

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)