c# - Linq to Entities 4.0 - 优化查询并在单个查询中多次调用数据库

标签 c# linq .net-4.0 linq-to-entities subquery

谁能告诉我下面的查询是多次调用数据库还是只调用一次?

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(),但我找不到其他方法,所以如果您有更好的优化代码,请随时分享!

提前致谢!

格瓦

最佳答案

这完全取决于您对 bizItems 变量的处理方式,因为在您仅运行此代码之后,将仅运行 COUNT(*) 查询.这是因为 item 包含一个 IQueryable,它是对查询(运行的意图)的描述,而不是操作的结果。查询只会在您开始迭代此查询时运行,方法是使用 foreach 或诸如 .Count() 之类的运算符。除此之外,BusinessProfileProducts 属性也可能包含 IQueryable

那么,让我们看看您可以使用这段代码做什么:

foreach (var item in bizItems.items)
{
    Console.WriteLine(item.BusinessLocation.City);

    foreach (var profile in item.BusinessProfile)
    {
        Console.WriteLine(profile.Name);
    }

    foreach (var product in item.Products)
    {
        Console.WriteLine(product.Price);
    }

    Console.WriteLine(item.Count);
    Console.WriteLine();
}

所以,如果你再问我,看看这段代码,有多少查询会被发送到数据库,我的答案是:2 + 2 * bizItems.items 中的项目数。所以查询的数量将在 2 到 (2 + 2 * pageSize) 之间。

关于c# - Linq to Entities 4.0 - 优化查询并在单个查询中多次调用数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3418115/

相关文章:

c# - 使用 Linq 按日期获取数据

.net-4.0 - NServiceBus 2.0.0.1219 不接收消息

vb.net - 错误 "Editor doesn'不支持文件扩展名“.VB”?

c# - 动态添加页脚到 ASP.NET GridView

c# - OrderByDescending with Skip and Take 在 LINQ 中显示错误

c# - 在 WCF Rest 中捕获 WebFaultException 的详细信息

c# - Gridview 显示空行

.net - 将 OrderedDictionary 转换为 Dictionary<string, string> 的更好方法

c# - ThreadPool.QueueUserWorkItem 中的最大排队元素

c# - 方法没有支持的 SQL 转换