Record caching

Topics: General
Jan 16, 2015 at 12:02 PM
Can someone tell if caching records directly will give problems?
Otherwise I have to map the properties first to a DTO or POCO class but that will result basically in the same class. The concerning record is a record which doesn't have a part and is queried only by a IRepository.
Jan 17, 2015 at 2:25 PM
Edited Jan 17, 2015 at 2:29 PM
Yes, it will get you into trouble. Record objects fetched via IRepository<T> are proxies bound to a session.
You'd have to either map records to cacheable POCOs or use NH stateless session instead of IRepository<T>.

Using stateless session is simple as this:
private ISessionFactoryHolder _sessionFactoryHolder;
using(var session = _sessionFactoryHolder.GetSessionFactory().OpenStatelessSession())
    var myTable = Session.Query<MyRecordClass>().Cacheable();
    // Do your stuff on the myTable like you'd do on IRepository<T>.Table
This way whatever comes from the query will be a simple POCO
It's similar to what happens under the hood inside the Repository<T> implementation, just with a different kind of session.

There are caveats though - you won't be able to fetch records with relations this way. In any other case, ie. when your records contain only simple type properties, this approach works very well.
Jan 17, 2015 at 4:17 PM
Fantastic answer. Thanks! I'm gonna try it.
Jan 18, 2015 at 12:40 PM
Very interesting, thanks for this awesome little tidbit pszmyd!
Jan 19, 2015 at 9:17 AM
Ok I found out that when using the syscache module (second level caching of NHibernate), the queries of the Repository class are already cached. Because I'm using syscache I don't need to cache the output manually. It was informative though :)