Is there a sample why Equals / GetHashCode should be overwritten in NHibernate?

I find many posts explaining that you should always override Equals / GetHashCode in the NHibernate entity class. If I do not use Sets, is this really necessary?

I just can't find a sample showing that missing Equals / GetHashCode can lead to unexpected and incorrect behavior. Everything seems perfect without them. It is really strange that everyone says that it is necessary, but no one can provide a sample that shows why this is necessary.

+7
source share
2 answers

Question has recently been included in SO when NHibernate selects N + 1, even if fetch is specified. The problem was with the missing Equals / GetHashCode implementation.

The answer refers to another similar question .

Here's another question regarding reasoning outside Equals / GetHashCode is canceled.

Nhibernate n + 1 with triple relationships. Want a medium object in triple
Nhibernate producing proxies despite choosing HQL
NHibernate: Reasons for Overriding Equals and GetHashCode
Why Equals and GetHashCode are So Important to NHibernate
Why is it important to override GetHashCode when the Equals method is overridden?


Edit

You do not need to redefine them all the time. This may be necessary if you use compound keys, multiple sessions with separate objects or stateless sessions.

If you work with only one session, NHibernate saves objects to the first level cache using an identification card. Comparison of objects in this case is performed by comparing identifiers.

In the above cases (single object, session without saving) NHibernate compares the actual objects, not their identifiers. By default, Object.Equals refers to equality. Thus, two objects are equal if they point to the same instance. You can have two instances with the same identifier, but Object.Equals will return false for them. This contrasts with the Entity definition :

An object that is not defined by its attributes, but rather a thread of continuity and its identity.

The JBoss Hibernate wiki has a good explanation in Equals and HashCode with a few code examples.

+11
source

In fact, there are only rare cases when this leads to side effects. But if you get them, they are pretty thin. Besides compound primary keys and dictionary keys, which always require the correct implementation of Equals / GetHashCode.

NH takes care of instantiating an object only once in memory, so comparing links by default should work ... if it werenโ€™t for lazy loading .

If you do not override Equals, you are having trouble working with proxies. There are always two instances: proxy and real entity . Both of them represent the same entity. Only with a correctly implemented Equals method can it be considered the same.

+4
source

All Articles