EF Core context not disposing of change tracking entities

.net-core asp.net-core c# entity-framework entity-framework-core

Question

Using EF Core 2.1 to insert 135k records. Once the request is finished, I would expect the context to be disposed of and along with it, the ChangeTracking entities to be cleared, however, it's holding on to all 135k records and using a lot of memory in the process.

We are using ASP.NET Core 2.1 and injecting the EF Context from the DI container. Since the DI container should dispose of the scoped context at the end of the request, it should not be holding on to these values. Even calling dispose manually at the end of the controller does not seem to affect the change tracking entities.

Below is the output of the heap view of the memory usage after the request has finished. Diving into the path, I'm seeing a lot of EF Core classes and strangely seeing a EntityQueryable instance for a different entity (System vs InvoicePendingItem).

Heap


The context is being registered in Startup.cs:

services.AddDbContext<EFContext>(options => options.UseMySql(
  GetDBConnectionString()
));
1
0
8/20/2019 5:45:54 PM

Popular Answer

Seems to be a question about: How should I manage DbContext Lifetime in MVC Core?

As for change tracking, it is enabled by default and is removed when you dispose of the context. However you can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false

context.Configuration.AutoDetectChangesEnabled = false;

Additionally, when you insert +100k items you should do that in batches of for example 2k for performance and memory reasons.

0
8/20/2019 6:17:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow