nHibernate update not working for existing entity

烈酒焚心 提交于 2020-01-13 19:40:11

问题


i am trying to update record with nHibernate. I tried several solutions, but none of them work (shows no error, bu data is alsno not updated).
First code:

MyRepository rep = new MyRepository(GetCurrentSession());
UserPost post = rep.GetById(id);
post.ValidTo = date;
rep.Update(post);

Second code:

ISession session = GetCurrentSession();
MyRepository rep = new MyRepository(GetCurrentSession());
UserPost post = rep.GetById(id);
post.ValidTo = date;
rep.Update(post);
session.Update(post);
session.Transaction.Commit();
session = null;

Maybe somedy has a suggestion?


回答1:


Is UserPost mapped correctly? Are you using .hbm.xml files (note the hbm) and the xml file is marked as an embedded resource?

In my experience if an entity is not mapped NHibernate doesn't complain nor throw an error.

Actually looking at your code in more detail you are not calling session.Save




回答2:


1) You need to flush the session if you are not using a transaction`:

var post = _session.Load<Post>(id); //assumes this record exists in the db
post.SomeAttribute=somenewvalue;
_session.SaveOrUpdate(post);
_session.Flush;

2) I don't see a transaction being started? You need to start a transaction to commit.

using(var transaction = _session.BeginTransaction()){
   _session.SaveOrUpdate(post);
   transaction.commit();
}



回答3:


using(var transaction = _session.BeginTransaction()){
   _session.SaveOrUpdate(post);
   transaction.commit();
}

I had this Batch Update returns rowcount = 0 but expected is 1 exception. But this works




回答4:


If you want to update some persist entity's fields you shouldn't call session.Update() or session.SaveOrUpdate(), you can use session.Flush() or transactions:

MyRepository rep = new MyRepository(GetCurrentSession());
UserPost post = rep.GetById(id);
post.ValidTo = date;
rep.Flush(); // session.Flush()

OR

using(var transaction = _session.BeginTransaction()){
   UserPost post = rep.GetById(id);
   post.ValidTo = date;
   transaction.commit();
}


来源:https://stackoverflow.com/questions/10414243/nhibernate-update-not-working-for-existing-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!