How to get NHibernate ISession to cache entity not retrieved by primary key

1.2k Views Asked by At

My 'user' entity is almost always retrieved by username, rather than by its integer surrogate key. Because the username is not the primary key, this means that the ISession won't cache it and repeatedly hits the database to get the same data.

Is there any way at all I can configure NHibernate to get the ISession to cache users retrieved by username?

3

There are 3 best solutions below

1
On BEST ANSWER

It seems the answer is in fact no. Yes, if you're using the second level cache, no if you are using the Session cache.

2
On

Yes, you can use NHibernate's natural-id element to accomplish this. See http://ayende.com/Blog/archive/2009/06/23/nhibernate-ltnatural-idgt.aspx, the example is exactly what you're asking for.

1
On

The "session cache" is actually not a cache, but an entity map.

My suggestion is that you enable the 2nd level cache for queries using a custom provider that stores items in the HttpContext.