简体   繁体   中英

Do I need to close EF core Dbcontext connection manually

I have use EF core for my web application and in there to initialize dbcontext I have use constructor dependency injection.

   private readonly ERPDB_GlobalContext _dbContext;
   public ProductCategoryController(ERPDB_GlobalContext dbContext)
   {
       _dbContext = dbContext;
       
   }

After using dependency injection I have directly use _dbcontext for CRUD operations without using a using scope. So I need to know without using a using scope after I did CRUD operation is connection is going to close automatically.

these are two examples I have use dbcontext without using scope to fetch data and save data to database

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();

I have read MSdoc and some articles and found that dbcontext is going to automatically close after the dbcontext object is destroy else connection is not open manually (But don't have much idea about what is manually open connection in EF core)

Need to clarify is it must to use using scope when creating dbContext while using dependency injection

The lifetime of a DbContext begins when the instance is created and ends when the instance is disposed. A DbContext instance is designed to be used for a single unit-of-work

A typical unit-of-work when using Entity Framework Core (EF Core) involves:

  1. Creation of a DbContext instance
  2. Tracking of entity instances by the context. Entities become tracked by Being returned from a query Being added or attached to the context
  3. Changes are made to the tracked entities as needed to implement the business rule
  4. SaveChanges or SaveChangesAsync is called. EF Core detects the changes made and writes them to the database.
  5. The DbContext instance is disposed

This answer is found in Microsoft docs thanks to @Genusatplay, for further reading you can refer DbContext Lifetime, Configuration, and Initialization .Under this link you can find how dbcontext is going to work when we use dependency injection and without dependency injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM