Setting nhibernate property-ref on one-to-many to property other than primary key fails

1.9k Views Asked by At

I am receiving this exception ONLY when I set the property-ref in my xml file.

Initializing[Domain.Entities.R#12345]-failed to lazily initialize a collection of role: Domain.Entities.R.LP, no session or session was closed

LP.hbm.xml
----------
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Domain.Entities" assembly="Domain">

<class name="LP" table="LP">
  <id name="Id">
    <column name="Id" sql-type="int" not-null="true"/>
  </id>

  <property name="AnotherField"/>
  <property name="PaymentDate"/>
  <property name="PaymentAmount"/>
</class>

</hibernate-mapping>


R.hbm.xml
---------
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Domain.Entities" assembly="Domain">
<class name="R" table="R">
<id name="Id">
  <column name="Id" not-null="true"/>
</id>

<property name="AnotherField"/>

<set name="LP">
  <key column="AnotherField" property-ref="AnotherField" />
  <one-to-many class="Domain.Entities.LP" not-found="ignore" />
</set>
</class>
</hibernate-mapping>

        IQueryable<Entities.R> query = _db.Query<Entities.R>();

        var query2 = _db.Query<Entities.LP>().ToList();

        var queryResults = query.ToList();

        Iesi.Collections.Generic.ISet<Entities.LP> lp; 
        try
        {
            lp = queryResults.First().LP;   <--- this fails with exception
        }
        catch (Exception ex) 
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            var lp2 = _db.Query<Entities.LP>().Take(100); <-- works just fine
        }

What I don't understand is why does lp2 get set fine, but lp fails? I know the data model isn't ideal, but it's what I have to work with for now. If I remove the property-ref from the xml file in nhprof I see it make the calls to the SQL table (with the wrong value so I get no data back), but it doesn't fail. This only occurs when I have the property-ref set.

Any help would be greatly appreciated. This is my first run with NH.

1

There are 1 best solutions below

3
Colin Grealy On

The error message is giving you the answer. Your set of LP objects in the R class is lazy loaded by default. This means you need to access the LP collection within a session.

Typically, you do this by getting an ISessionFactory and calling OpenSession in a using block. Access the collection in the using block and you should be fine.