将断开连接的对象附加到 NHibernate 会话;最佳实践? [英] Attaching a disconnected object to an NHibernate session; best practice?

查看:25
本文介绍了将断开连接的对象附加到 NHibernate 会话;最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的存储库在 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.

我遇到的问题是,使用这个模型时,代码必须知道"用户需要什么,并使用 UnitOfWorkNHUtil.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() 方法的情况下,我看到推荐使用三种方法将对象与新会话相关联.其中哪一项是完成工作的最佳做​​法?

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?

答:

if(!Session.Contains(domainObject))
    Session.Update(domainObject);

乙:

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 - 关联一个未更改的对象
  • 合并 - 如果对象存在于当前会话然后它被更新随着合并对象的变化,否则与Lock相同

这篇关于将断开连接的对象附加到 NHibernate 会话;最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆