我需要用“假”数据填充我的数据库,以便对其执行一些压力测试。
为此,我写了一些简单直接的代码来输入数据。
它运行超过 7 个表,为每个表创建一个对象,并使用以下命令添加它:
System.Data.Entity.Add(TEntity)
如下:
context.MyObject.Add(MyObjInstance);
我每隔几百个对象就保存一次。
现在这是减慢速度的方式,即使没有提交。 (我指的是几千个对象的小时数)。
有没有更快的方法来添加(大约几千个)对象?
像 addAll()
之类的东西,或者任何其他可以加速 Add
方法的东西?
谢谢。
最佳答案
可能是因为重复调用了DetectChanges()
。某些 EF 函数会自动调用此方法。参见 here .
If you are tracking a lot of entities in your context and you call one of these methods many times in a loop, then you may get significant performance improvements by turning off detection of changes for the duration of the loop
设置
context.Configuration.AutoDetectChangesEnabled = false;
执行密集的 .Add()
操作并设置:
context.Configuration.AutoDetectChangesEnabled = true;
在调用 SaveChanges()
之前。
还可以考虑对部分批量操作使用新的上下文,因为上下文跟踪的实体越多,它的性能就越差。
关于c# - Entity Framework - 将简单的实体添加到上下文中非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16954498/