问题描述
我的存储库在UnitOfWork
模型中工作;所有操作,无论是检索操作还是持久性操作,都必须在IDisposable
UnitOfWork
令牌对象的范围内执行,该对象在后台与执行所需工作的Session
相关联.因此,基本模式是:
My repository works in a UnitOfWork
model; all operations, whether retrieval or persistence, must be performed within the scope of an IDisposable
UnitOfWork
token object, which behind the scenes is associated with a Session
that performs the work requested. So, the basic pattern is:
using (var uow = repo.BeginUnitOfWork())
{
try
{
//DB operations here; all repo methods require passing in uow.
...
repo.CommitUnitOfWork(uow);
}
catch(Exception)
{
repo.RollbackUnitOfWork(uow);
throw;
}
}
我还实现了一些包装方法,使您可以指定将在此框架中执行的lambda或委托,从而无需每次都实现所有这些脚手架.
I've also implemented some wrapper methods that allow you to specify a lambda or delegate that will be executed in this framework, relieving the need to implement all this scaffolding every time.
我遇到的问题是,使用此模型,代码必须知道"用户的需求,并渴望在UnitOfWork
中使用NHUtil.Initialize()
加载它.一旦将UOW放置在using块的末尾,与任何PersistentBags
关联的Session都将关闭,因此无法对其进行评估.由于急于预先加载所有内容并不总是可行的,并且某种程度地违反了延迟加载ORM的目的,因此我正在实现Attach()
方法.
The problem I'm having is that using this model, code must "know" what the user needs, and eager-load it using NHUtil.Initialize()
within the UnitOfWork
. Once the UOW is disposed at the end of the using block, the Session associated with any PersistentBags
is closed, and so they cannot be evaluated. As eager-loading everything up front is not always feasible and kind of defeats the purpose of a lazy-loading ORM, I am implementing an Attach()
method.
这是问题;在没有内置的ISession.Attach()
方法的情况下,我推荐使用三种方法将对象与新的Session关联.完成工作的最佳方法是哪一种?
Here's the question; In the absence of a built-in ISession.Attach()
method, there are three methods I've seen recommended to associate an object with a new Session. Which of them is the best practice to get the job done?
A:
if(!Session.Contains(domainObject))
Session.Update(domainObject);
B:
Session.Merge(domainObject);
C:
Session.Lock(domainObject, LockMode.None);
推荐答案
D:以上都不是.通过保持您的UOW太短来有效地禁用延迟加载,并且无法达到延迟加载ORM的目的.您必须按照正常操作将断开连接的对象重新关联的事实,这意味着您的工作单元边界是错误的.
D: None of the above. Effectively disabling lazy-loading by keeping your UOW too short and defeats the purpose of a lazy-loading ORM. The fact that you have to re-associate disconnected objects as normal operations means that your unit of work boundaries are wrong.
合并,更新和锁定都有不同的用途.如果您坚持使用当前的体系结构,那么Lock可能就是您想要的.
Merge, Update, and Lock all have different purposes. If you're stuck with your current architecture then Lock is probably what you want.
- 更新-关联更改的对象
- 锁定-关联未更改的对象
- 合并-如果对象存在于当前会话,然后更新通过合并对象的更改,否则与Lock相同
- Update - associates a changed object
- Lock - associates an unchanged object
- Merge - if the object exists in thecurrent session then it is updatedwith changes from the merged object,otherwise it's the same as Lock
这篇关于将断开连接的对象附加到NHibernate会话;最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!