Not*_*sxl 8 .net c# nhibernate transactions flush
我需要在NHibernate的工作单元中执行两个操作:事务性(实体保存)和非事务性操作.
由于无事务操作无法回滚,如果我在执行非事务操作(并最终提交事务)之前保存实体,我仍然会得到一个事务行为:
问题:使用如下代码,NHibernate将不会执行实际的sql插入,直到调用transaction.Commit()(在内部调用session.Flush()):
using (var transaction = session.BeginTransaction())
{
session.Save(entity);
NotTransactionalOperationBasedOn(entity);
transaction.Commit(); // the actual sql insert will be executed here
}
Run Code Online (Sandbox Code Playgroud)
使用这样的代码,如果Sql Insert失败则为时已晚:NotTransactionalOperation已执行.要在执行NotTransactionalOperation之前执行实际的SQL插入,我必须在session.Save()之前明确调用session.Flush():
using (var transaction = session.BeginTransaction())
{
session.Save(entity);
session.Flush(); // the actual sql insert will be executed here
NotTransactionalOperationBasedOn(entity);
transaction.Commit();
}
Run Code Online (Sandbox Code Playgroud)
代码有效,但......在提交事务之前调用session.Flush()是最佳做法吗?如果没有,是否有更好的方法来实现相同的结果?
刷新意味着 NHibernate 将确保所有更改都保存到数据库中。也就是说,它将确保执行所有必要的 SQL 语句。当事务失败并因此回滚时,所有这些更改都将被恢复。因此,我认为这样做没有问题(但是您必须记住,您的实体可能不处于有效状态,因为事务已失败)。
但是......我实际上没有看到问题:当非事务性过程失败时,问题是什么?由于该过程是非事务性的,我想它对数据库保存的信息没有影响?或者,这段代码的作用是什么?
如果它是非事务性的,为什么不能在工作单元之外进行呢?
当保存失败时,我想您将确保不仅事务被回滚,而且异常也会被抛出到堆栈上,直到遇到错误处理程序,这可能意味着您的非事务处理程序代码也不会被执行:
using( var transaction = session.BeginTransaction() )
{
repository.Save (entity);
transaction.Commit(); // error, exception is thrown.
}
NonTransactionalCode (entity); // this line will not be executed, since the exception will be thrown up the stack until a suitable catch block is encountered.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10099 次 |
最近记录: |