Hey StackOverflow friends,
I have a situation where I would like to be able to cache some nhibernate entites, most likely by means of cached queries. I am trying to figure out the best way to structure this in an MVC 4 project. My NHibernate layer resides in a seperate layer and I am using Windsor for my DI.
I would like to be able to do the following. Say for instance I have a UserTypes table in the database, the PK is a GUID/uniqueidentifier. I want to be able to do a Session.Load(guid) instead of having to pay for the select everytime I need this data.
Here is some code. I don’t like the GUID’s hardcoded like this. I suppose I could stuff the GUIDs in the web.config but I would like something more automatic in case something changes,
nhsession.Save(new User
{
UserType = nhsession.Load<UserType>(Guid.Parse("BE4A74B1-5B21-4109-AD69-A0AF00FC879F")),
UserSetting = nhsession.Load<UserSetting>(Guid.Parse("CB0B2053-E173-408D-A991-A09B00E45330")),
UserName = userDto.UserName,
Password = hash,
Salt = salt,
IsLockedOut = 0,
InvalidLoginAttempts = 0,
ActivationCode = activationCode,
Active = active,
LastLoginDate = DateTime.Now,
DateCreated = DateTime.Now,
LastUpdated = DateTime.Now,
Profile = new Profile
{
EmailAddress = userDto.UserName,
Active = 1,
DateCreated = DateTime.Now,
LastUpdated = DateTime.Now
}
});
NHibernate provides support for first and second level caching. The scope of the first level cache is limited to the session itself. However, the second level cache is available to all sessions within the session factory. Ayende Rahien posted a detailed description on NHibernate caching here: http://nhibernate.hibernatingrhinos.com/28/first-and-second-level-caching-in-nhibernate