【发布时间】:2021-08-17 02:57:59
【问题描述】:
我为我的 Web 应用程序使用了 EF 核心,并在那里初始化 dbcontext 我使用了构造函数依赖注入。
private readonly ERPDB_GlobalContext _dbContext;
public ProductCategoryController(ERPDB_GlobalContext dbContext)
{
_dbContext = dbContext;
}
使用依赖注入后,我直接使用 _dbcontext 进行 CRUD 操作,而不使用 using 范围。所以我需要知道在我执行 CRUD 操作后不使用 using 范围连接是否会自动关闭。
这是我使用 dbcontext 而不使用范围来获取数据并将数据保存到数据库的两个示例
var category = _dbContext.ProductCategories.Where(c => c.CompanyId == cmp).ToList();
ProductCategories productCategory = new ProductCategories
{
ProductCateId = Guid.NewGuid(),
ProductCateName = model.ProductCateName,
CompanyId = companyId,
};
_dbContext.ProductCategories.Add(productCategory);
_dbContext.SaveChanges();
我阅读了MSdoc和一些文章,发现dbcontext对象被销毁后dbcontext会自动关闭,否则连接不会手动打开(但对EF核心中手动打开的连接不太了解)
需要澄清的是在使用依赖注入的同时创建dbContext时必须使用使用范围
【问题讨论】:
-
感谢@Genusatplay 阅读我找到了答案。
标签: c# mysql entity-framework .net-core