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 ?

Leri
  • 12,367
  • 7
  • 43
  • 60

1 Answers1

2

Please note - that GetHashCode and Equals should implement the same logic. 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.

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.

Vadim
  • 2,847
  • 15
  • 18
  • Yeah I think this is the problem. This is why I was thinking to leave that alone and just implement my own simplified .Equals. Maybe I was thinking to call it .Same or something like that. Do you think this is a reasonable thing to do? If I did this then how could I code that so that it works like .Equals ? –  Aug 11 '13 at 07:07
  • If equality in your domain is what is written in your Equals, then use it. Just modify your GetHashCode accordingly (Here's probably the best way - http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode). You do want Dictionaries and EF to work according to your domain model, don't you? In specific cases of need, you may use other methods like Same. But something as basic as object equality should be properly defined in your domain. – Vadim Aug 11 '13 at 07:25