nHibernate update not working for existing entity

8.2k views Asked by At

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?

4

There are 4 answers

1
Rippo On BEST ANSWER

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

enter image description here

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

0
Samuel Goldenbaum On

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();
}
0
Anton On

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();
}
0
Shan On
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