简体   繁体   English

用方法替换.Equals而不是覆盖它是否合理?

[英]Is it reasonable to replace .Equals with a method rather than override it?

I am using Entity Framework 5 and I tried to override .Equals and .GetHashCode 我正在使用Entity Framework 5,我试图覆盖.Equals和.GetHashCode

public class Students    {
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int Age {get; set;} 

    public override bool Equals(object obj)
    {
        return this.Equals(obj as Students);
    }

    public bool Equals(Students other)
    {
        if (other == null)
            return false;

        return this.Age.Equals(other.Age) &&
            (
                this.Name == other.Name ||
                this.Name != null &&
                this.Name.Equals(other.Name)
            );
    }

    public override int GetHashCode()
    {
        return PersonId.GetHashCode();
    }
}

However my very simple method does not seem to work and I get errors from EF saying: Conflicting changes to the role 然而,我的非常简单的方法似乎不起作用,我从EF得到错误说:角色的变化冲突

I am thinking this is due to the way EF does comparisons. 我认为这是由于EF做比较的方式。

Is there a way that I can provide my own method and call this in the same way as .Equals ? 有没有办法可以提供我自己的方法,并以与.Equals相同的方式调用它? I was thinking maybe I could code a method called .Same and use that. 我想也许我可以编写一个名为.Same的方法并使用它。 Is that something that is reasonable to do. 这是否合理。 If I did that and I wanted to compare two objects then how could I code it and call it ? 如果我这样做,我想比较两个对象,那么我怎么能编码并调用它?

Please note - that GetHashCode and Equals should implement the same logic. 请注意 - GetHashCode和Equals应该实现相同的逻辑。 Namely - objects that are equal should have the same hash code. 即 - 相等的对象应具有相同的哈希码。 This is not the case here, where the hash code comes from the Id while equality has nothing to do with the Id. 这不是这里的情况,其中哈希码来自Id,而相等与Id无关。

If you override one, you must override both. 如果覆盖一个,则必须覆盖它们。

You can use whatever logic you wish in your domain, but EF and others will probably use the defaults and you must keep them consistent. 您可以在域中使用您希望的任何逻辑,但EF和其他人可能会使用默认值,您必须保持它们的一致性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM