Entity Framework 个实体的最佳做法覆盖 Equals 和 GetHashCode

Best practices for Entity Framework entities override Equals and GetHashCode

我想检查两个内部具有 one-to-many 关系的实体之间的相等性。

很明显,我覆盖了 Object.Equals 方法,但随后我收到 CS0659 编译器警告:'class' overrides Object.Equals(object o) but does not override Object.GetHashCode().

我覆盖了 Object.GetHashCode,但是 Resharper 告诉我 GetHashCode 方法应该 return 所有对象生命周期的相同结果,并将用于可变对象。 (docs)

public class Computer
{
    public long Id { get; set; }
    public ICollection<GPU> GPUs { get; set; } = new List<GPU>();

    public override bool Equals(object obj)
    {
        return obj is Computer computer &&
               GPUs.All(computer.GPUs.Contains);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(GPUs);
    }
}

public class GPU
{
    public long Id { get; set; }
    public int? Cores { get; set; } = null;

    public override bool Equals(object obj)
    {
        return obj is GPU gpu &&
               Cores == gpu.Cores;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Cores);
    }
}

我不知道我应该喜欢什么:

Entity Framework 使用它自己的智能方法来检测对象是否相等。例如,如果您调用 SaveChanges,将使用此方法:获取对象的值与更新对象的值相匹配,以检测是否需要 SQL 更新。

我不确定你的相等性定义是否会扰乱这种相等性检查,导致数据库中更新一些未更改的项目,或者更糟糕的是,一些更改的数据不会在数据库中更新。

数据库相等性

请记住,您的实体 classes(您放入 DbSet<...> 中的 classes)代表数据库中的 tables 和关系在 table 之间。

什么时候应该认为从数据库中提取的两个项目表示同一对象?是当他们有相同的价值观时吗?我们不能在同一个数据库中有两个出生于 7 月 4 日的名为 "John Doe" 的人吗?

检测从数据库中提取的两个 Persons 代表相同 Person 的唯一方法是检查 ID。一些非主键值不同的事实只是告诉你改变的数据在数据库中没有更新,而不是不同Person

覆盖等于与创建 EqualityComparer

我的建议是,让您的 table 表示尽可能简单:只有 table 的列(非虚拟属性)和 table 之间的关系s(虚拟属性)。没有成员,没有方法,什么都没有。

如果您需要额外的功能,请创建 classes 的扩展功能。如果您需要非标准的相等比较方法,请创建一个单独的相等比较器。 class 的用户可以决定是要使用默认比较方法还是您的特殊比较方法。

这与各种字符串比较器都具有可比性:StringComparer.OrdinalIgnorCaseStringComparer.InvariantCulture

回到你的问题

在我看来,您想要一个不检查 Id 值的 Gpu 比较器:具有不同 Id 的两个项目,但其他属性的相同值被认为是相等的。

class GpuComparer : EqualityComparer<Gpu>
{
    public static IEqualityComparer<Gpu> IgnoreIdComparer {get;} = new GpuComparer()

    public override bool Equals(Gpu x, Gpu y)
    {
        if (x == null) return y == null; // true if both null, false if x null but y not
        if (y == null) return false;     // because x not null
        if (Object.ReferenceEquals(x, y)) return true;
        if (x.GetType() != y.GetType()) return false;

        // if here, we know x and y both not null, and of same type.
        // compare all properties for equality
        return x.Cores == y.Cores;
    }
    public override int GetHasCode(Gpu x)
    {
        if (x == null) throw new ArgumentNullException(nameof(x));

         // note: I want a different Hash for x.Cores == null than x.Cores == 0!

         return (x.Cores.HasValue) ? return x.Cores.Value.GetHashCode() : -78546;
         // -78546 is just a value I expect that is not used often as Cores;
    }
}

请注意,我添加了相同类型的测试,因为如果 y 是 Gpu 的派生 class,并且您会忽略它们不是同一类型,那么可能是 Equals(x, y),但不是 Equals(y, x),这是等式函数的先决条件之一

用法:

IEqualityComparer<Gpu> gpuIgnoreIdComparer = GpuComparer.IgnoreIdComparer;
Gpu x = new Gpu {Id = 0, Cores = null}
Gpu y = new Gpu {Id = 1, Cores = null}

bool sameExceptForId = gpuIgnoreIdComparer.Equals(x, y);

x 和 y 将被视为相等

HashSet<Gpu> hashSetIgnoringIds = new HashSet<Gpu>(GpuComparer.IgnoreIdComparer);
hashSetIgnoringIds.Add(x);
bool containsY = hashSetIgnoringIds.Contains(y); // expect true

计算机的比较器将是相似的。除了您忘记检查 null 和类型之外,我发现您想要进行相等性检查的方式存在其他一些问题:

  • 可以将 null 分配给您的 Gpus 集合。你必须解决这个问题,它不会抛出异常。 Gpus 为空的计算机是否等于 Gpus 为零的计算机?
  • 显然 Gpus 的顺序对你来说并不重要:[1, 3] 等于 [3, 1]
  • 显然某个GPU出现的次数并不重要:[1, 1, 3]等于[1, 3, 3]?

.

class IgnoreIdComputerComparer : EqualityComparer<Computer>
{
    public static IEqualityComparer NoIdComparer {get} = new IgnoreIdComputerCompare();


    public override bool (Computer x, Computer y)
    {
        if (x == null) return y == null;not null
        if (y == null) return false;
        if (Object.ReferenceEquals(x, y)) return true;
        if (x.GetType() != y.GetType())  return false;

        // equal if both GPU collections null or empty,
        // or any element in X.Gpu is also in Y.Gpu ignoring duplicates
        // using the Gpu IgnoreIdComparer
        if (x.Gpus == null || x.Gpus.Count == 0)
            return y.Gpus == null || y.Gpus.Count == 0;

        // equal if same elements, ignoring duplicates:
        HashSet<Gpu> xGpus = new HashSet<Gpu>(x, GpuComparer.IgnoreIdComparer);
        return xGpush.EqualSet(y);
    }

    public override int GetHashCode(Computer x)
    {
        if (x == null) throw new ArgumentNullException(nameof(x));

        if (x.Gpus == null || x.Gpus.Count == 0) return -784120;

         HashSet<Gpu> xGpus = new HashSet<Gpu>(x, GpuComparer.IgnoreIdComparer);
         return xGpus.Sum(gpu => gpu);
    }
}

TODO:如果您将使用大量 Gpus,请考虑更智能的 GetHashCode