在foreach循环内外调用SaveChanges()之间有什么区别? [英] Any difference between calling SaveChanges() inside and outside a foreach loop?

查看:254
本文介绍了在foreach循环内外调用SaveChanges()之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在foreach循环中或在循环外部调用EF SaveChanges()之间是否存在性能优势/技术差异(假设在循环内部调用EF实体进行了更改)?

Is there any performance benefit/technical differences between calling EF SaveChanges() in a foreach loop or outside a loop, assuming a change is made to an EF entity inside the loop?

推荐答案

是!

如果在循环中调用它,EF将回写对每个实体 的数据库更改(每个实体将在其自己的单独交易中)。

If you call it inside the loop, EF will write back the changes to the database for every single entity (and every entity will be in its own, separate transaction).

相反,您将进行所有更改,EF将在循环后一次全部写回它们(一次所有实体的交易)。

The other way around, you'll make all your changes and EF will write them back all at once after the loop (in one single transaction for all entities together).

作为一般的经验法则(实际上没有看到您的代码),尝试使 .SaveChanges()的调用减少。 code>

As a general rule of thumb (without actually seeing your code) try to have as few calls to .SaveChanges() as possible.

一个具有50个更改的呼叫通常比50个具有1个更改的呼叫更好/更快/更有效率。

One call with 50 changes is typically much better / faster / more efficient than 50 calls for 1 change each.

这篇关于在foreach循环内外调用SaveChanges()之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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