简体   繁体   English

Nhibernate实体更新一致性

[英]Nhibernate entity update consistence

If I have a User object that contains a collection of UserPhoto object currently being persisted with a cascading update using NHibernate. 如果我有一个User对象,其中包含UserPhoto对象的集合,该对象当前正在使用NHibernate进行级联更新而持久化。 So you save the user object and all UserPhoto's get saved as well. 因此,您保存了用户对象,同时也保存了所有UserPhoto。

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? 有没有一种方法可以通过仅保存UserPhoto来上传新的UserPhoto,而不必保存整个用户对象层次结构?

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 这将使用正确的UserId将行保存在数据库中,但是如果我这样做的话

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. 我猜想NHibernate最初在代码中获取用户对象时会先将其缓存,然后在数据库级别添加userphoto,但是NHibernate缓存中仍包含较早的User对象,该对象未引用新照片,我添加新照片后,需要刷新该用户对象的NHibernate缓存。 Is this correct and how do I do that refresh? 这是正确的,我该如何刷新? Am I using NHibernate correctly? 我是否正确使用NHibernate?

Thanks 谢谢

the NHibernate ISession has a first level cache or entity cache which is important to hvae reference equality when loading the user twice. NHibernate ISession具有一级缓存或实体缓存,这对于在两次加载用户时实现引用相等很重要。 You have to 你必须

  • call session.Refresh(user) or 呼叫session.Refresh(user)
  • add the photo to the users collection 将照片添加到用户收藏夹

i 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM