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:
You forgot to mention that this means you should use an ID which is not assigned by the DB.
Otherwise the value of the ID will change once you call Session.SaveOrUpdate, as a consequence your ID changes which is not good if you already have that object in a Hashset or something.
I guess :-)
This is true :) I was using the ID as an example (the "such as an ID part"), if you've got an ID that's assigned by the database, then you're going to need to have a bit more logic for testing equality, which will include testing the ID, but if it hasn't been set, then you're going to end up having to do a more complex business rule check.
Hello,
are you sure that ==/!= needs to be overridden for safely lazy loading associations? Manning makes no mention of this in NHibernate in Action. Overriding Equals is enough.
It is not required, but it will avoid much headache down the road to override !=/==. I have found that certain scenario's during lazy loading do take advantage of those overrides, and during debug processes where I'm breaking in the equality overrides, NHibernate was breaking in there during equality operations on lazy loaded entities.
This was a few versions back in NHibernate that I had noticed it, so it's possible this isn't the case anymore. Regardless, I still prefer to override both for my own == and != checks.
Post a Comment