How to get NHibernate ISession to cache entity not

2019-07-14 07:27发布

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条回答
女痞
2楼-- · 2019-07-14 07:49

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.

查看更多
【Aperson】
3楼-- · 2019-07-14 07:53

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.

查看更多
Lonely孤独者°
4楼-- · 2019-07-14 08:06

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.

查看更多
登录 后发表回答