需要帮助理解Nhibernate事务和如何不重复代码(如果可能) [英] Need help understanding Nhibernate Transactions and how not to duplicate code (if possible)
问题描述
我了解您应该始终使用交易。我也看到NHibernate.ITransaction实现Dispose,所以我需要包装我的ITransaction对象在using语句。所以,这是否意味着对于每个非只读存储库方法(即更新,编辑...)我必须声明:
I understand that you should always use transactions. I also see that NHibernate.ITransaction implement a Dispose, so I need to wrap my ITransaction object in a using statement. So, does that mean that for every non-readonly repository method (i.e. update, edit...) I have to declare:
using (ITransaction _transaction = _session.BeginTransaction(//isolationlevel)) {
//procedure code here
}
有一种方式,我可以包装这(我不看到我可以)。
Is there a way that I can wrap this (I am not seeing that I can).
此外,
using (_transaction = _session.BeginTransaction(IsolationLevel.ReadCommitted) {
try {
_session.SaveOrUpdate(entity);
try {
_transaction.Commit();
catch (//some exception ex) {
_transaction.RollBack();
}
}
catch (//some exception ex) {
//log ex
}
}
还是有一个更好的方法,如在会话和事务方法相同的尝试/捕获?
Or is there a better way such as having both session and transaction methods in the same try/catch?
感谢,
推荐答案
当使用ISession直接是这样的:(你应该使用一个事务,即使是读取)
The recommended practice when using the ISession directly is this: (you should use a transaction even for reads)
using(var session = factory.OpenSession())
using(var tx = session.BeginTransaction())
{
// all the code that uses the session goes here
// use session to load and/or save entity
}
这基本上是创建一个工作单元。
This is basically creating an unit of work.
根据您的操作上下文(Web请求,wcf请求),您可能希望将所有操作都包含在单个工作单元内。有关网络请求,请参阅此 WCF操作。 this 。
Depending on your operation context ( web request, wcf request ) you might want to have all the operation inside a single unit of work. For web request see this for WCF operation see this.
还有Sixto Saez说调用SaveOrUpdate是一种气味。在大多数情况下,您有以下两种情况之一:
Also as Sixto Saez said calling SaveOrUpdate is a smell. In most of the cases you have one of these two cases:
1您创建一个新实体并调用session.Save(entity);
1 You create a new entity and call session.Save(entity);
或
2从会话中获取一个或多个实体(使用Get / Load或通过查询),修改实体和更改将被nhibernate保存在会话处理上。 (除非你改变了会话刷新模式,但这不是重点)。
2 You get an entity or more from the session ( with Get/Load or by query ), modify the entity and the changes will be saved by nhibernate on session disposal. ( unless you change the session flush mode but that is not the point ).
这篇关于需要帮助理解Nhibernate事务和如何不重复代码(如果可能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!