Override Equals, GetHashCode, and the !=/== operators - This is pretty basic. If you're using NHibernate, as a general rule of thumb for a best practice, you should override all of these functions. Why? Because by default your applications will attempt to do a referential check to determine if they're equal, or if the object already exists in the collection. Implementing your own routine allows you to check the business properties of an entity, such as the ID or business data, to determine equality. To put it simply, NHibernate won't work correctly if you don't do this.
Overriding !=/== is important when you've set your associations to lazyload, because NHibernate will generate proxies for those objects to support the lazyloading concept. Those proxies rely on these two overrides to determine object equality based on business rules (again, such as the ID/business rules).
Also important to note, testing the ID property of a lazy loaded (proxied) object does not load the object from the database. The ID property is free, that's how the proxy knows about which entity to load from the database. In an ideal world, you should try and work all of your equality rules to use the ID so you can take advantage of all of NHibernate's optimizations.
4 comments: