首页 > 解决方案 > '不支持客户端 GroupBy。'

问题描述

我正在尝试GroupBy()在北风数据库中运行命令这是我的代码

using(var ctx = new TempContext())
{
    var customer = (from s in ctx.Customers
                    group s by s.LastName into custByLN
                    select custByLN);
    foreach(var val in customer)
    {
        Console.WriteLine(val.Key);
        {
            foreach(var element in val)
            {
                Console.WriteLine(element.LastName);
            }
        }
    }
}

它给System.InvalidOperationException: 'Client side GroupBy is not supported'

标签: entity-frameworklinqentity-framework-core

解决方案


显然,您正在尝试为 LastName 创建具有相同值的客户组。一些数据库管理系统不支持 GroupBy,尽管这种情况很少见,因为 Grouping 是一种非常常见的数据库操作。

要查看您的数据库管理系统是否支持分组,请尝试使用 GroupBy 方法语法。以 , 结尾ToList来执行 GroupBy:

var customerGroupsWithSameLastName = dbContext.Customers.GroupBy(

    // Parameter KeySelector: make groups of Customers with same value for LastName:
    customer => customer.LastName)
.ToList();

如果这可行,则 DbContext 与之通信的 DBMS 接受 GroupBy。

结果是组列表。每个 Group 对象都实现IGrouping<string, Customer>,这意味着每个 Group 都有一个 Key:该组中所有客户的公共 LastName。该组是(不是具有)具有此姓氏的所有客户的序列。

顺便说一句:一个更有用的 GroupBy 重载有一个额外的参数:resultSelector。使用 resultSelector 您可以影响输出:它不是IGrouping对象序列,而是您使用函数指定的对象序列。

此函数有两个输入参数:通用 LastName 和具有此 LastName 值的所有客户。此函数的返回值是您的输出序列的元素之一:

var result = dbContext.Customers.GroupBy(
    customer => customer.LastName,

    // parameter resultSelector: take the lastName and all Customers with this LastName
    // to make one new:
    (lastName, customersWithThisLastName) => new
    {
        LastName = lastName,
        Count = customersWithThisLastName.Count(),

        FirstNames = customersWithThisLastName.Select(customer => customer.FirstName)
                                              .ToList(),
        ... // etc
    })
    .ToList();

回到你的问题

如果上面的代码显示您的 DBMS 不支持该功能,您可以让您的本地进程进行分组:

var result = dbContext.Customer
    // if possible: limit the number of customers that you fetch
    .Where(customer => ...)

    // if possible: limit the customer properties that you fetch
    .Select(customer => new {...})

    // Transfer the remaining data to your local process:
    .AsEnumerable()

    // Now your local process can do the GroupBy:
    .GroupBy(customer => customer.LastName)
    .ToList();

由于您选择了完整的客户,所有客户数据无论如何都会被传输,因此如果您让本地进程执行 GroupBy 并不会造成太大损失,除了 DBMS 可能比本地进程更优化以更快地进行分组.

警告:数据库管理系统在选择数据方面进行了极其优化。数据库查询中较慢的部分之一是将所选数据从 DBMS 传输到本地进程。因此,如果您必须使用AsEnumerable(),您应该意识到您将传输到现在为止选择的所有数据。AsEnumerable()确保在;之后不转移任何你无论如何都不会使用的东西。因此,如果您只对 and 感兴趣FirstNameLastName请不要传输主键、外键、地址等。让您的 DBMS 执行Where and Select`


推荐阅读