EF Core context not disposing of change tracking entities

和自甴很熟 提交于 2021-01-28 08:18:05

问题


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).


The context is being registered in Startup.cs:

services.AddDbContext<EFContext>(options => options.UseMySql(
  GetDBConnectionString()
));

回答1:


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.




回答2:


You can implement the IDispose interface in your classes correctly and manage how the class will be destroyed when it is no longer used, implement the interface and use the Dispose Pattern.

Read about in this documentation: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose



来源:https://stackoverflow.com/questions/57578551/ef-core-context-not-disposing-of-change-tracking-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!