NHibernate -failed to lazily initialize a collection of role

后端 未结 3 1281
-上瘾入骨i
-上瘾入骨i 2021-02-07 03:04

I have the following seemingly simple scenario, however I\'m still pretty new to NHibernate.

When trying to load the following model for an Edit action on my Controller:

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-07 03:44

    "If we want to access the order line items (after the session has been closed) we get an exception. Since the session is closed NHibernate cannot lazily load the order line items for us. We can show this behavior with the following test method"

    [Test]
    [ExpectedException(typeof(LazyInitializationException))]
    public void Accessing_customer_of_order_after_session_is_closed_throws()
    {
      Order fromDb;
      using (ISession session = SessionFactory.OpenSession())
          fromDb = session.Get(_order.Id);
    
      // trying to access the Customer of the order, will throw exception
      // Note: at this point the session is already closed
      string name = fromDb.Customer.CompanyName;
    }
    

    "Eagerly loading with the NHibernateUtil class If you know you need have access to related objects of the order entity you can use the NHibernateUtil class to initialize the related objects (that is: to fetch them from the database)."

    [Test]
    public void Can_initialize_customer_of_order_with_nhibernate_util()
    {
        Order fromDb;
    
        using (ISession session = SessionFactory.OpenSession())
        {
           fromDb = session.Get(_order.Id);
    
           NHibernateUtil.Initialize(fromDb.Customer);
        } 
    
        Assert.IsTrue(NHibernateUtil.IsInitialized(fromDb.Customer));
        Assert.IsFalse(NHibernateUtil.IsInitialized(fromDb.OrderLines));
    
    }
    

    Reference: http://nhibernate.info/doc/howto/various/lazy-loading-eager-loading.html

提交回复
热议问题