NHibernate commit db changes without explict call to save or update

后端 未结 3 1632
太阳男子
太阳男子 2020-12-16 23:54

I use Nhibernate 2.0 in ASP.NET. I start the transaction at the begging of the page and commit the transaction at the end. During the page: - I get an object - I change the

3条回答
  •  悲哀的现实
    2020-12-17 00:43

    I just ran into this same problem. Eyston's answer was very helpful, explaining that it doesn't matter whether or not you call ISession.Update(object) or SaveOrUpdate(object), NH tracks the changes, and committing the transaction will commit the changes.

    There are a few ways you can accomplish your validation then, to prevent changes going to the database. Do all of your validation and (possible) saving in a separate transaction.

    using (ITransaction tx = session.BeginTransaction())
    {
        // get your object
        // do your validation
    
        // if you pass validation:
        tx.Commit();
    
        // if not, roll it back
        tx.Rollback();
    }
    

    I have solved my problem a bit differently. If my validation fails, I don't want any updates to occur for that particular object, so I simply evict it from the session.

    if (!myObj.ValidateForSave())
    {
        session.Evict(myObj);
    }
    

    Doing it that way, you can stick to your single transaction, starting it at the beginning of the page, and committing it at the end. If your object failed validation, it won't be in the session, and no changes will be persisted to the database.

提交回复
热议问题