You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#三层架构+工作单元模式:数据无法保存、CurrentTransaction为空的修复

问题修复:三层架构+Unit of Work模式下数据无法写入的解决方法

你的代码核心问题是Repository与UnitOfWork各自实例化了独立的DbContext对象。Repository里的实体变更被记录在自己的Context中,但UnitOfWork调用Commit()时操作的是另一个完全无关的Context,自然无法将变更同步到数据库,同时因为没有共享Context,也不会有事务上下文(CurrentTransaction为null)。

以下是具体修复步骤:

1. 修改Repository,通过构造函数注入DbContext

移除Repository的无参构造,改为接收外部传入的FrontendContext,确保和UnitOfWork使用同一个实例:

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class 
{
    private readonly FrontendContext context;
    private readonly DbSet<TEntity> dbSet;

    // 构造函数注入共享的Context
    public Repository(FrontendContext context){
        this.context = context;
        dbSet = context.Set<TEntity>();
    }

    public void Create (TEntity entity){
        dbSet.Add(entity);
    }

    public IEnumerable<TEntity> GetAll(){
        return  dbSet.ToList();
    }
}

2. 修改UnitOfWork,传递共享Context给Repository

让UnitOfWork通过构造函数获取Context,并在创建Repository时将该实例传递过去:

public class UnitOfWork : IUnitOfWork
{
    private readonly FrontendContext context;
    
    // 构造函数注入Context,不再手动实例化
    public UnitOfWork(FrontendContext context){
        this.context = context;
    }
    
    public IRepository<TEntity> RepositoryBase<TEntity>() where TEntity : class {
        // 创建Repository时传入共享的Context
        return new Repository<TEntity>(context);
    }
    
    public void Commit() => context.SaveChanges();
}

3. 优化依赖注入配置,注册DbContext

在Program.cs中注册DbContext,让ASP.NET Core的DI容器统一管理实例生命周期:

// 注册DbContext,配置连接字符串
builder.Services.AddDbContext<FrontendContext>(options =>
    options.UseSqlServer(@"server=(local);Database=CredentialBug;Trusted_Connection=True;TrustServerCertificate=True"));

// 保持UnitOfWork的注册
builder.Services.AddTransient<IUnitOfWork, UnitOfWork>();

4. 移除Context中的硬编码配置(可选但推荐)

既然已经通过DI配置了连接字符串,可删除FrontendContext中的OnConfiguring方法,让DI接管配置:

public class FrontendContext : DbContext
{
    // 通过构造函数注入配置选项
    public FrontendContext(DbContextOptions<FrontendContext> options) : base(options)
    {
    }

    public DbSet<Person> People { get; set; }
}

修改完成后,Repository与UnitOfWork将共享同一个DbContext实例:调用Repository.Create()时实体变更会被记录到该Context中,执行Commit()即可将所有变更同步到数据库,Context的变更跟踪和事务上下文也能正常工作。

内容的提问来源于stack exchange,提问作者mamad2559

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 10:35:22