首页 > 解决方案 > 将实体状态设置为 Add 后,Entity Framework Core 未保存对数据库的更改

问题描述

在我的例子中,我有一个依赖于范围服务的单例服务,它是一个 DbContext 实现。

单例服务基本上是一个数据访问层,它对 SQL 服务器数据库执行 CRUD 操作。

在数据访问层,我注入了 IServiceScopeFactory 来为每个请求获取我的 DbContext 实例。

以下代码块显示了数据访问实现的示例:

public class Repository<IEntity> : IRepository<IEntity> where IEntity : BaseEntity
{
    private readonly IServiceScopeFactory _scopeFactory;

    public Repository(
        IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public void Add(IEntity entity)
    {
        using (var scope = _scopeFactory.CreateScope())
        {
            var _context = scope.ServiceProvider.GetRequiredService<PCPSContext>();
            _context.Set<IEntity>().Add(entity);
            scope.Dispose();
        }

    }

    public Task<int> SaveChangesAsync()
    {
        Task<int> result;
        using (var scope = _scopeFactory.CreateScope())
        {
            var _context = scope.ServiceProvider.GetRequiredService<PCPSContext>();
            result = _context.SaveChangesAsync();
            scope.Dispose();
        }

        return result;
    }
}

数据访问服务的注册:

            services.AddSingleton(typeof(IRepository<>), typeof(Repository<>));

dbContext 的注册:

var connection = configuration.GetConnectionString("PCPS_CS");
        LogManager.Configuration.Variables["connectionString"] = connection;
        services.AddDbContext<PCPSContext>(options =>
        options.UseSqlServer(connection, b => b.MigrationsAssembly("PCPS.API")));

问题是,使用 EFcore 保存更改后,更改并没有反映在 SQL Server 数据库中,在添加实体的过程中也没有发生异常。

我很想知道是什么导致数据没有反映在数据库中。

标签: c#asp.netentity-framework-core

解决方案


由于您在async没有await.

改变:

result = _context.SaveChangesAsync();

result = await _context.SaveChangesAsync();

也不需要Disposeusing块内调用。该对象在 using 块结束后自动处置。


推荐阅读