我正在使用NHibernate将一些数据插入表A.如果表A事务失败,我想更新表B中的状态.如何检查是否失败?
以下是我目前的代码:
// Add userId to Receiver
Receiver receiver = new Receiver();
receiver.User = User.GetById(Convert.ToInt32(listItem.Value));
receiver.Notification = Notification.GetById(notification.NotificationId);
receiver.Save();
Run Code Online (Sandbox Code Playgroud)
我在哪里调用NHibernate事务?如果失败,我在哪里调用NHibernate Rollback并更新表B状态?
看一下关于异常处理的官方NHibernate文档:http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-exceptions
using ( ISession session = sessionFactory.OpenSession() )
{
using ( ITransaction transaction = session.BeginTransaction() )
{
try
{
// Do your save/update here for Table A
transaction.Commit();
}
catch( Exception e )
{
// Your save or update failed so this is where you
// could capture that info and update your Table B
transaction.Rollback();
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的记忆,你实际上不必调用tx.Rollback(),因为当你的代码离开使用块时,它会自动执行,但是再一次,我记不起来了.尝试一下,如果它不像我刚才描述的那样,你可以在catch中手动回滚.
| 归档时间: |
|
| 查看次数: |
5353 次 |
| 最近记录: |