Asp.net-Mvc
NHibernate - 延遲初始化角色集合失敗
我有以下看似簡單的場景,但是我對 NHibernate 還是很陌生。
當嘗試為我的控制器上的編輯操作載入以下模型時:
控制器的編輯操作:
public ActionResult Edit(Guid id) { return View(_repository.GetById(id)); }儲存庫:
public SomeModel GetById(Guid id) { using (ISession session = NHibernateSessionManager.Instance.GetSession()) return session.Get<SomeModel >(id); }模型:
public class SomeModel { public virtual string Content { get; set; } public virtual IList<SomeOtherModel> SomeOtherModel { get; set; } }我收到以下錯誤:
- 延遲初始化角色集合失敗:SomeOtherModel,沒有會話或會話已關閉
我在這裡想念什麼?
問題是您在模型
GetById方法中創建並關閉了會話。(using語句關閉會話)會話必須在整個業務事務期間可用。有幾種方法可以實現這一點。您可以將 NHibernate 配置為使用會話工廠 GetCurrentSession 方法。請參閱nhibernate.info或Code Project 上的此文章。
public SomeModel GetById(Guid id) { // no using keyword here, take the session from the manager which // manages it as configured ISession session = NHibernateSessionManager.Instance.GetSession(); return session.Get<SomeModel >(id); }我不使用這個。我編寫了自己的交易服務,它允許以下內容:
using (TransactionService.CreateTransactionScope()) { // same session is used by any repository var entity = xyRepository.Get(id); // session still there and allows lazy loading entity.Roles.Add(new Role()); // all changes made in memory a flushed to the db TransactionService.Commit(); }無論您如何實現它,會話和事務應該與業務事務(或系統功能)一樣長。除非你不能依賴事務隔離也不能回滾整個事情。