Linq to Entities 4.0 - 优化查询并在单个查询中多次调用数据库
谁能告诉我以下查询是多次调用数据库还是只调用一次数据库?
var bizItems = new
{
items = (
from bl in db.rc_BusinessLocations
orderby bl.rc_BusinessProfiles.BusinessName
select new BusinessLocationItem
{
BusinessLocation = bl,
BusinessProfile = bl.rc_BusinessProfiles,
Products = bl.rc_InventoryProducts_Business
})
.Skip(pageSkip).Take(pageSize),
Count = db.rc_BusinessLocations.Count()
};
我真的需要从查询中获取 Count() ,但我找不到其他方法来做到这一点,所以如果您有一些更好的优化代码,请随时分享!
提前致谢!
格瓦尔
Can anyone tell me if the following query calls the database multiple times or just once?
var bizItems = new
{
items = (
from bl in db.rc_BusinessLocations
orderby bl.rc_BusinessProfiles.BusinessName
select new BusinessLocationItem
{
BusinessLocation = bl,
BusinessProfile = bl.rc_BusinessProfiles,
Products = bl.rc_InventoryProducts_Business
})
.Skip(pageSkip).Take(pageSize),
Count = db.rc_BusinessLocations.Count()
};
I really need to get the Count() out of the query and I couldn't find another way to do it so if you have some better optimized code, feel free to share it!
Thanks in advance!
Gwar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这完全取决于您对
bizItems
变量执行的操作,因为在运行此代码后,只会运行COUNT(*)
查询。这是因为item
包含一个IQueryable
,它是查询的描述(运行意图),而不是操作的结果。仅当您使用foreach
或.Count()
等运算符开始迭代此查询时,该查询才会运行。除此之外,BusinessProfile
和Products
属性可能还会包含IQueryable
。那么,让我们看看你可能用这段代码做什么:
所以,如果你再问我,看看这段代码,有多少查询将发送到数据库,我的答案是:2 + 2 * 项目数在 bizItems.items 中。因此查询数量将在 2 到 (2 + 2 * pageSize) 之间。
It totally depends on what you are doing with the
bizItems
variable, because after you've ran just this code, only aCOUNT(*)
query will have ran. This is because theitem
contains anIQueryable
which is a description of a query (an intent to run), not the result of the operation. The query will only run when you start iterating this query, by usingforeach
or an operator such as.Count()
. Besides this, theBusinessProfile
andProducts
properties will probably also containIQueryable
s.So, let's take a look at what you might do with this code:
So, if you ask me again, looking at this code, how many queries will be sent to the database, my answer is: 2 + 2 * the number of items in
bizItems.items
. So the number of queries will be between 2 and (2 + 2 * pageSize).您应该查看 Scott Guthrie 的 关于使用 LINQ to SQL 调试可视化工具的帖子。这将使您能够准确地查看将从 LINQ 语句生成的 SQL。
You should check out Scott Guthrie's post on using the LINQ to SQL Debug Visualizer. This will allow you to see exactly the SQL that will be generated from your LINQ statement.
这肯定会导致两次调用。
This will definitely result in two calls.