I would like to use the Iesi.Collections HashedSet class for entity collections in NHibernate. The functionality I want is that duplicate entities cannot be added. I would like entities to be considered duplicate if they share the Id (i.e. primary key) field, or, if they have Id == 0 (i.e. unsaved), then certain key properties are compared instead.
I notice that by default the HashedSet appears to define duplica开发者_运维问答tes using reference equality. What do I need to change in order to get the HashedSet to define duplication according to the rules I described above? (E.g. override .Equals, override ==, etc).
Equals and GetHashCode must always be overridden together. The documentation for GetHashCode states:
Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly.
Jon Skeet's answer to this question provides additional information.
Overriding the equality operators is optional but I recommend it.
You need to override GetHashCode method.
精彩评论