0

I am using Entity Framework 5 and I tried to override .Equals and .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

I am thinking this is due to the way EF does comparisons.

Is there a way that I can provide my own method and call this in the same way as .Equals ? I was thinking maybe I could code a method called .Same and use that. 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 ?

4

1 回答 1

2

请注意 - GetHashCode 和 Equals 应该实现相同的逻辑。即 - 相等的对象应该具有相同的哈希码。这不是这里的情况,其中哈希码来自 Id,而相等与 Id 无关。

如果您覆盖其中一个,则必须同时覆盖两者。

您可以在您的域中使用您希望使用的任何逻辑,但 EF 和其他人可能会使用默认值,并且您必须保持它们的一致性。

于 2013-08-11T07:02:23.780 回答