DbContext is very slow when adding and deleting

[亡魂溺海] 提交于 2019-11-28 04:19:14

Try to add this to your DbContext tests:

dbContext.Configuration.AutoDetectChangesEnabled = false;

// Now do all your changes

dbContext.ChangeTracker.DetectChanges();
dbContext.SaveChanges();

and try to run your tests again.

There was some architectural change in DbContext API which checks changes in entities every time you Add, Attach or Delete anything from the context. In ObjectContext API this detection run only when you triggered SaveChanges. It is better solution for most common scenarios but it requires special handling for mass data processing.

In EF6 you can now use AddRange and RemoveRange on DbSet.

From to the documentation on the links:

Note that if AutoDetectChangesEnabled is set to true (which is the default), then DetectChanges will be called once before {adding,deleting} any entities and will not be called again. This means that in some situations {Add,Remove}Range may perform significantly better than calling {Add,Remove} multiple times would do.

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