Reputation: 5055
If I have a User object that contains a collection of UserPhoto object currently being persisted with a cascading update using NHibernate. So you save the user object and all UserPhoto's get saved as well.
Is there a way I can just upload a new UserPhoto by just saving the UserPhoto, without having to save the entire user object hierachy?
I have tried
userPhoto.User = user; // to set the parent object which will provide the UserPhoto with the correct UserId when saving it
session.Save(userPhoto);
Which saves the row in the DB fine with the correct UserId, but if I then do
session.Get<User>(userId)
it doesnt contain the new photo. I'm guessing that NHibernate is caching the user object initially when I get it earlier in the code, then I add the userphoto at DB level but the NHibernate cache still contains the earlier User object which doesn't reference the new photo, and I need to refresh the NHibernate cache for that user object after adding the new photo. Is this correct and how do I do that refresh? Am I using NHibernate correctly?
Thanks
Upvotes: 0
Views: 187
Reputation: 30813
the NHibernate ISession has a first level cache or entity cache which is important to hvae reference equality when loading the user twice. You have to
session.Refresh(user)
ori would favor the second because it prevents a broken model (user) while the session is active and doesn't need a db roundtrip.
if you do not know if the user is already loaded and just need the reference do
var user = session.Load<User>(userId);
userPhoto.User = user;
session.Save(userPhoto);
if (NHibernateUtil.IsInitialized(user))
{
user.Photos.Add(userPhoto);
}
Upvotes: 1