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

查看:25
本文介绍了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 实例(SystemInvoicePendingItem).

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 Lifetime?

至于更改跟踪,它默认启用并在您处理上下文时删除.但是,您也可以通过将 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天全站免登陆