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

使用EF+PostgreSQL开发Web API时POST数据无法存入数据库

问题分析与解决方案

核心问题是你创建了Applicant实体对象,但没有将其注册到EF Core的上下文(DbContext)中,直接调用SaveChangesAsync时,EF Core不知道需要保存这个新实体,所以数据不会写入数据库。

具体修复步骤

  1. 给基础仓库添加实体添加方法
    在BaseRepository<T>中补充Add方法,让EF Core跟踪新实体:

    public class BaseRepository<T> : IRepository<T> where T : class
    {
        protected readonly AppDbContext context;
    
        public BaseRepository(AppDbContext context)
        {
            this.context = context;
        }
    
        // 新增Add方法
        public async Task Add(T entity)
        {
            await context.Set<T>().AddAsync(entity);
        }
    
        // . . .
    
        public async Task Save()
        {
            await context.SaveChangesAsync();
        }
    }
    

    同时确保IApplicantRepository接口也包含这个Add方法的定义。

  2. 在服务层添加实体到仓库
    修改ApplicantService的CreateApplicant方法,在调用Save前先将创建好的Applicant实体添加到仓库:

    public async Task<ApplicantResponse> CreateApplicant(CreateApplicantRequest request)
    {
        Applicant applicant = request.ToCreateApplicant();
        await Validate(request.Email, request.Phone, request.SocialSecurity, request.DriversLicense);
        // 先添加实体到上下文跟踪
        await repository.Add(applicant);
        await repository.Save();
    
        return applicant.ToApplicantResponse();
    }
    

额外排查点

  • 检查Validate方法是否存在异常被静默捕获(比如内部try-catch未抛出异常,但逻辑上阻止了后续操作),可以在方法内添加日志或调试断点确认执行流程。
  • 确认AppDbContext的DI生命周期配置为Scoped(ASP.NET Core默认配置),如果是Singleton可能导致上下文状态异常。
  • 可以在Save方法中检查SaveChangesAsync的返回值(返回受影响的行数),如果返回0说明没有数据被写入,进一步排查原因:
    public async Task Save()
    {
        int affectedRows = await context.SaveChangesAsync();
        // 可添加日志记录affectedRows,确认是否有数据被保存
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:45:04