Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force NHibernate to hit the database when querying for an entity?

Tags:

nhibernate

I have a situation where I need NHibernate to ignore its caches and just hit the database because the data has changed (another user on another computer has changed the data). How is this possible? So far I have had no luck. Get, Load, Linq query, doesn't matter. NHibernate is not getting the most recent data.

like image 845
Chris Holmes Avatar asked Mar 26 '10 21:03

Chris Holmes


1 Answers

For second level cache, you must clear it using ISessionFactory.Evict(typeof(T));. For first level cache, you can simply call ISession.Clear(); .

And if you don't know when to clear a second level cache, you should send some info from another app to this one (via sockets, or webservice...). If that is not possible, you can create a table in the database that tells you when data in database was last modified and then check the record in that table. If it was modified, then you clear the caches. Just be sure the record gets updated every time some other app changes the database (you can do that with triggers or check system tables).

If you use triggers, don't forget to ignore the record if you update with nhibernate. You can do that with some variable that has the last update time set to it and compare it with that.

like image 81
dmonlord Avatar answered Oct 16 '22 20:10

dmonlord