问题描述
我正在考虑使用NHibernate实现IRepository模式,但我有一个问题,就是我无法回答搜索网络的问题.
I'm looking into implementing the IRepository pattern using NHibernate and I have question that I've not been able to answer searching the net.
假设我有3个存储库,PersonRepository,PersonAddressRepository和PersonAccountRepository.现在,假设业务逻辑规定存在一个调用PersonRepository.Deactivate(),PersonAddressRepository.Deactivate()和PersonAccountRepository.Deactivate()的停用Person"过程.
Assume I have 3 Repositories, PersonRepository, PersonAddressRepository and PersonAccountRepository. Now assume that business logic dictates that there be an "Deactivate Person" process that calls PersonRepository.Deactivate(), PersonAddressRepository.Deactivate() and PersonAccountRepository.Deactivate().
我希望能够做一些类似的事情.
I want to be able to do something along the lines of..
using (ITransaction transaction = session.BeginTransaction()) {
session.Update(Person);
session.Update(PersonAddress);
session.Update(PersonAccount);
}
因此,如果这些更新中的任何一个失败,整个过程将在数据库中回滚.现在,我对NHibernate的理解是,您只能为每个对象创建一个Session.
So that if any of those updates fail that the entire process rolls back within the database. Now at the moment my understanding of NHibernate is you can only create a Session per object so..
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Person).Assembly);
ISessionFactory sessionFactory = cfg.BuildSessionFactory();
using (ISession session = sessionFactory.OpenSession()) {
using (ITransaction transaction = session.BeginTransaction()) {
session.Save(Person);
}
这是正确的还是我弄错了?关于多表更新和关于NHibernate的事务的最佳做法是什么?
Is this correct or am I mistaken? What are the best practices for Transactions regarding multi table updates and Transactions with regards to NHibernate.
谢谢.
推荐答案
您不应在存储库或其他波纹管"中创建事务.事务由应用程序逻辑定义.这是我在事务处理中看到的最常见的错误之一.
You should not create transactions in the repositories or somewhere else "bellow". Transactions are defined by the application logic. This is one of the most common mistakes I see in transaction handling.
我写了一个管理交易的交易服务:
I wrote a transaction service which manages the transactions:
using (TransactionService.CreateTransactionScope())
{
repositoryA.DoX();
repositoryB.DoY();
TransactionService.Commit();
}
存储库正在通过服务从公开交易中获取会话:
The repository is getting the session with an open transaction from the service:
TransactionService.Session.CreateQuery("...");
根据您的环境,您需要使其更加复杂.例如,会话可能对业务逻辑不可见,应将其置于其他接口等上.
Depending on your environment, you need to make it a bit more complicated. For instance, the session may not be visible to the business logic and should to be put onto another interface etc.
这篇关于使用IRepository的C#共享事务和NHibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!