ActiveRecord: Loading Records by Primary Key
I was reviewing some code today for a project that uses ActiveRecord. One of the things that stood out for me was the use of a query to find objects by their primary key. There's two reasons this raised a red flag for me:
- ActiveRecord already contains a built-in method for locating objects by their primary key: Find().
- Ayende just made a post about a month ago about why you shouldn't use queries to find objects by their primary key in NHibernate (which ActiveRecord uses under the hood). You loose some optimizations that are built-in to NHibernate. Read Ayende's post for more details.
So if you're an ActiveRecord user, how can you control which Session method to use – Get() or Load()? Easy:
- ActiveRecordBase.Find() uses Session.Load to load objects by primary key.
- ActiveRecordBase.TryFind() uses Session.Get to load objects by primary key.
And if you're ever wondering how ActiveRecord works under the hood (or how some NHibernate concepts are used), grab the source and look around!