EF Core上下文未处理变更跟踪实体 [英] EF Core context not disposing of change tracking entities

查看:54
本文介绍了EF Core上下文未处理变更跟踪实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用EF Core 2.1插入135k记录.请求完成后,我希望可以处理上下文,并与它一起清除 ChangeTracking 实体,但是,它将保留所有135k记录并在其中使用大量内存过程.

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.

我们正在使用ASP.NET Core 2.1,并从DI容器注入EF上下文.由于DI容器应在请求结束时释放范围内的上下文,因此它不应保留这些值.甚至在控制器末端手动调用dispose似乎也不会影响更改跟踪实体.

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.

以下是请求完成后内存使用情况的堆视图的输出.深入探讨,我看到了很多EF Core类,并且奇怪地看到了另一个实体的 EntityQueryable 实例( System InvoicePendingItem ).

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

上下文正在 Startup.cs 中注册:

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

推荐答案

似乎是关于以下问题:如何在MVC Core中管理DbContext生存期?

对于更改跟踪,默认情况下已启用它,并且在处置上下文时将其删除.但是,您也可以通过将DbContext的AutoDetectChangesEnabled属性设置为false来禁用更改跟踪.

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;

此外,由于性能和内存原因,当您插入+ 100k项时,应分批执行,例如2k.

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

这篇关于EF Core上下文未处理变更跟踪实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆