实体框架实体的最佳实践覆盖 Equals 和 GetHashCode

bar*_*iro 3 c# entity-framework object-equality

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

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

我覆盖了Object.GetHashCode,但是 Resharper 告诉我,该GetHashCode方法应该为所有对象生命周期返回相同的结果,并将在可变对象中使用。(文档

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道我应该选择什么:

  • 重写该Equals方法而不重写GetHashCode,或者
  • 用不可变数据覆盖GetHashCode

Har*_*lse 6

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

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

数据库平等

请记住,您的实体类(您放入的类DbSet<...>)代表数据库中的表以及表之间的关系。

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

检测Persons从数据库中提取的两个是否表示相同的唯一方法Person是检查 Id。某些非主键值不同的事实仅告诉您更改的数据未在数据库中更新,而不是表明它是不同的Person

覆盖等于与创建 EqualityComparer

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

如果您需要额外的功能,请创建类的扩展函数。如果您需要非标准相等比较方法,请创建单独的相等比较器。您班级的用户可以决定是否要使用默认比较方法或您的特殊比较方法。

这都可以与各种字符串比较器进行比较: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;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我添加了相同类型的测试,因为如果 y 是 Gpu 的派生类,并且您会忽略它们不是同一类型,那么可能是 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);
Run Code Online (Sandbox Code Playgroud)

x 和 y 将被视为相等

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

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

  • 可以将 null 分配给您的 GPU 集合。您必须解决这个问题,使其不会引发异常。具有 0 Gpus 的计算机等于具有 0 Gpus 的计算机吗?
  • 显然 GPU 的顺序对你来说并不重要: [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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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