I find a lot of posts where it is explained that one should always override Equals/GetHashCode on a NHibernate entity class. If I don’t use Sets, is this really necessary?
I simply can’t find a sample where it is shown that missing Equals/GetHashCode can lead to unexpected and wrong behaviour. Everything seems to work perfectly without them. This is really strange that everyone says this is necessary but no one can provide a sample which shows why this is needed .
There was a question on SO recently about NHibernate doing select N+1 even if
fetchis specified. The problem was with missingEquals/GetHashCodeimplementation.The answer links to another similar question.
Here’s another question on reasoning behind
Equals/GetHashCodeoverrides.Nhibernate n+1 with ternary relationship. Want the middle entity in the ternary
Nhibernate producing proxy despite HQL fetch
NHibernate: Reasons for overriding Equals and GetHashCode
Why Equals and GetHashCode are so important to NHibernate
Why is it important to override GetHashCode when Equals method is overridden?
Edit
You don’t need to override them all the time. It may be necessary if you are using composite keys, multiple sessions with detached entities or stateless sessions.
If you are working with a single session only, NHibernate stores the entities to first level cache using an identity map. Entity comparison in that case is done by comparing ids.
In cases above (detached entity, stateless session), NHibernate compares actual entities, not their ids. By default,
Object.Equalsdoes reference equality. So two objects are equal if they point to the exact same instance. You might have two instances with the same identity, butObject.Equalswould returnfalsefor them. This is in contrast with theEntitydefinition:JBoss Hibernate wiki has a good explanation on
EqualsandHashCodewith few code examples.