【问题标题】:Group by not working in Entity Framework Core通过不在 Entity Framework Core 中工作进行分组
【发布时间】:2022-11-09 04:02:37
【问题描述】:

我正在开发 EF Core 3.1 中的项目,但该版本可能与这个问题无关,因为我对 group by 有一个简单的例子的问题。

我的原始查询很长,所以在创建查询的过程中,我编写了稍后在selectgroup-by 中使用的模型,例如:

public class GroupClass 
{ 
    public int PropA { get; set; }
}

我认为问题在于加入结果,但即使是这个模型的简单示例也不起作用:

int[] testArray = { 1, 2, 3, 3, 3, 3, 3, 3 };
var result = (from a in testArray
              group a by new GroupClass
              {
                  PropA = a,
              } into g
              select new ModelClass
              {
                  PropA = g.Key.PropA,
              }).ToList();
Console.WriteLine(result.Count);
Result: 8 
Expected/wanted result: 3

很明显,group-by 比不上3==3,但是我该怎么办呢?我对流利的语法有同样的问题。

这是 rextester 上的完整代码:example

【问题讨论】:

    标签: c# entity-framework linq entity-framework-core grouping


    【解决方案1】:

    问题是EqualsGetHashCode 没有定义(默认情况下Equals 比较内存位置)。完成这项工作的一种方法是使用匿名对象:

    group a by new
    {
       PropA = a,
    } into g
    

    这是因为 CLR 为您创建了这些方法,如 documentation 中所述

    因为匿名类型的 Equals 和 GetHashCode 方法是根据属性的 Equals 和 GetHashCode 方法定义的,所以相同匿名类型的两个实例只有在它们的所有属性都相等时才相等。

    现在要使其与group-by 的模型一起使用,您应该实现EqualsGetHashCode

    public class GroupClass
    {
        public int PropA { get; set; }
        
        public override bool Equals(object o)
        {
            if (o == null || GetType() != o.GetType())
            {
                return false;
            }
            
            var other = o as GroupClassWorking;
            return this.PropA == other.PropA;
        }
        
        public override int GetHashCode()
        {
            return PropA.GetHashCode();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2017-07-29
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 2018-04-08
      相关资源
      最近更新 更多