Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8459899
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T13:27:22+00:00 2026-06-10T13:27:22+00:00

I have objects of which some have Lists of Documents, other Objects, … whatever.

  • 0

I have objects of which some have Lists of Documents, other Objects, … whatever. I do not want to use lazy=false on the relationship because it makes the application very slow. I can reattach objects with Lock, so other properties or one-to-many relationships load when they should. But for collections I always get “could not initialize a collection” if I try to access them. It does not work if I call Lock(obj) on the object that is connected to that location.

I want my mapping to look like this:

<set name="DocumentList" table="material_document" cascade="all" lazy="true">
  <key column="material_id"/>
  <many-to-many class="Document">
    <column name="document_id"/>
  </many-to-many>
</set>

Is there a method to reattach? Or is there a mapping setting?

update1:

this is the mapping on the material side:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
<class name="Material" table="material">
<!-- Defining PK -->
<id name="Id" type="integer" column="id">
    <generator class="sequence">
      <param name="sequence">material_id_seq</param>
    </generator>
</id>
<!-- Defining Properties -->
<!-- Defining FK-Relations -->
<set name="DocumentList" table="material_document" cascade="all" lazy="false">
  <key column="material_id"/>
  <many-to-many class="Document">
    <column name="document_id"/>
  </many-to-many>
</set>

The Document mapping file does not have any information about the relationship. The database name is alright, everything else works. The tables are called material, material_document and document. My classes are public and the properties public virtual. What can be wrong with my entities? Do you mean something with the data is wrong or something could have happened to the objects in the program…?

List material = LoadAllMaterials();
//some code, that causes the session to be closed, a new session will be opened
foreach (Document d in material.DocumentList) { //causes the exception
    //do something
}

Before that, I want to fetch the documents, without loading them beforehand.

update 2:
how I currently reattach objects:
I set force true when I know there is a proxy and it doesn’t work another way… And I have to check if it’s in the session because evict throws an Exception if I call it on an object that is not in the session.

public void Reattach(Type type, BaseObject o, bool force)
{
    bool inSession = o.IsInSession();

    if (force && inSession)
    {
        GetSession().Evict(o);
        GetSession().Lock(type.ToString(), o, LockMode.None);
    }
    else {

        o = (BaseObject)GetSession().GetSessionImplementation().PersistenceContext.Unproxy(o);

        if (!inSession) {

            GetSession().Lock(type.ToString(), o, LockMode.None);
        }
    }
}

and this is my IsInSession() method:

public virtual bool IsInSession() {

    ISession session = HibernateSessionManager.Instance.GetSession();

    var pers = session.GetSessionImplementation()
          .GetEntityPersister(GetType().ToString(), this);

    NHibernate.Engine.EntityKey key = new NHibernate.Engine.EntityKey(Id,
        pers, EntityMode.Poco);

    bool isInSession = false;

    try
    {
        object entity = session.GetSessionImplementation().PersistenceContext.GetEntity(key);

        if (entity != null)
        {
            isInSession = true;
        }
    }
    catch (NonUniqueObjectException) {}

    return isInSession;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T13:27:24+00:00Added an answer on June 10, 2026 at 1:27 pm

    I do see that you have lazy=”false” in one of your mappings…NHibernate uses lazy loading by default so I would remove all of the lazy=”false” and lazy=”true” statements from your mappings and just go with the NHibernate defaults.

    I created the following NUnit tests and both tests pass so I wasn’t able to duplicate your issue which means it’s either your lazy=”false” mapping stuff or some other issue… it’s always difficult to diagnose these issues without have the full application in front of you…

    Using the following test case, I was able to create the following error:
    “Initializing[SampleApplication.Customer#19]-failed to lazily initialize a collection of role: SampleApplication.Customer.Addresses, no session or session was closed”

    [Test]
    public void Testing_A_Detached_Entity()
    {
        // Arrange
        var sessionFactory = ObjectFactory.GetInstance<ISessionFactory>();
    
        Customer customer = null;
    
        using ( ISession session = sessionFactory.OpenSession() )
        {
            using ( ITransaction tx = session.BeginTransaction() )
            {
                customer = session.Query<Customer>()
                    .Where( x => x.CustomerNbr == 19 )
                    .FirstOrDefault();
            }
        }
    
        // Act
        TestDelegate actionToPerform = () =>
           {
               // Looping over this child collection should throw an Exception
               // because we no longer have an active NHibernate session
               foreach ( var address in customer.Addresses )
               {
    
               }
           };
    
        // Assert
        Assert.Throws<NHibernate.LazyInitializationException>( actionToPerform );
    }
    

    Using the following test case and using NHibernate’s session.Lock() method, I was able to successfully reattach the detached object and obtain a count on my child collection.

    [Test]
    public void Testing_Reattaching_A_Detached_Entity()
    {
        // Arrange
        var sessionFactory = ObjectFactory.GetInstance<ISessionFactory>();
    
        Customer customer = null;
    
        using ( ISession session = sessionFactory.OpenSession() )
        {
            using ( ITransaction tx = session.BeginTransaction() )
            {
                customer = session.Query<Customer>()
                    .Where( x => x.CustomerNbr == 19 )
                    .FirstOrDefault();
            }
        }
    
        // Act
        ISession newSession = sessionFactory.OpenSession();
    
        newSession.Lock( customer, LockMode.None );
    
        // Assert
        Assert.That( customer.Addresses.Count > 0 );
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a list of objects, some of which can be null. I want
I have some objects which will be used in the same manor. This object
I have an XSD file which is used to generate some objects which are
Some of my PHP domain objects have properties which should be set from outside
I have a user control which uses objects as inner properties (some code is
I have created data sources from my objects in my project, some of which
What I want to have is a custom object which provides some events. For
When we want to have new objects for some class, and if we already
I have an ActiveX object which extends some functions. I have a web page
I have an object config which has some properties. I can export this ok,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.