c# - 将实体状态设置为 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 数据库中,在添加实体的过程中也没有发生异常。
我很想知道是什么导致数据没有反映在数据库中。
解决方案
由于您在async
没有await
.
改变:
result = _context.SaveChangesAsync();
至
result = await _context.SaveChangesAsync();
也不需要Dispose
在using
块内调用。该对象在 using 块结束后自动处置。
推荐阅读
- typo3 - 如何使用扩展和站点包定义外部 CSS 的加载顺序
- string - 如何在 Erlang 中读取大小为 6GB 的文本文件?
- python - 合并 3 个数据帧,其中 2 个数据帧具有唯一 ID,但第 3 个数据帧具有其他 2 个唯一 ID 的组合
- java - 如果数据以单词“OPTIONS”开头,则数据不会到达服务器套接字
- vue.js - 如何在 v-html vuejs nuxt 中传递组件
- scala - 播放模板文件的import语句中的_root_是什么?
- fastapi - 如何正确返回状态码作为响应?
- python - 自动下载公共 GDrive 文件夹中的大文件
- hibernate - 带有可分页和子查询的 Spring JPA 导致查询语法错误
- spring-boot - 如何在没有 STOMP 的情况下使用 Spring 和 websockets 实现“while(true)”代码?