我有一个性能问题,关于LINQ如何使用foreach在实体框架中的可查询实体上执行.
I have a performance question regarding how LINQ performs with a foreach over an queryable entities from Entity Framework.
两者做的更好(更快)
foreach(var thing in myentities.GetThemAll())或
foreach(var thing in myentities.GetThemAll().ToList())第一个示例实际上会导致myentities.GetThemAll().Count()(+1?)次到数据库的每次旅行都收集一行吗?
Will the first example actually result in myentities.GetThemAll().Count() (+1 ?) trips to the database each collecting one row?
推荐答案如果只需要遍历元素而不调用ToList(),则更好.这是因为当我们调用它时,将触发相应查询的立即执行,并将创建一个内存中的集合.
It is better, if you have only to iterate through your elements to not call ToList(). This is because when we call it, an immediate execution of the corresponding query is triggered and one in memory collection will be created.
如果不调用ToList,则将避免创建用于保存查询结果的内存中集合.
If you don't call ToList you will avoid the creation of the in memory collection that will hold the results of your query.
无论您采用第一种方法,还是第二种方法,都将一次往返数据库.
Either you follow the first way, either the second, you will make one round trip to the database.
更多推荐
与LINQ to Entities一起使用foreach时是否需要ToList
发布评论