Problem with eager load polymorphic associations using Linq and NHibernate

Posted by Voislav on Stack Overflow See other posts from Stack Overflow or by Voislav
Published on 2010-04-13T19:19:37Z Indexed on 2010/04/13 19:23 UTC
Read the original article Hit count: 461

Is it possible to eagerly load polymorphic association using Linq and NH?

For example: Company is base class, Department is inherited from Company, and Company has association Employees to the User (one-to-many) and also association to the Country (many-to-one). Here is mapping part related to inherited class (without User and Country classes):

<class name="Company" discriminator-value="Company">
    <id name="Id" type="int" unsaved-value="0" access="nosetter.camelcase-underscore">
        <generator class="native"></generator>
    </id>
    <discriminator column="OrganizationUnit" type="string" length="10" not-null="true"/>
    <property name="Name" type="string" length="50" not-null="true"/>
    <many-to-one name="Country" class="Country" column="CountryId" not-null ="false" foreign-key="FK_Company_CountryId" access="field.camelcase-underscore" />
    <set name="Departments" inverse="true" lazy="true" access="field.camelcase-underscore">
        <key column="DepartmentParentId" not-null="false" foreign-key="FK_Department_DepartmentParentId"></key>
        <one-to-many class="Department"></one-to-many>
    </set>
    <set name="Employees" inverse="true" lazy="true" access="field.camelcase-underscore">
        <key column="CompanyId" not-null="false" foreign-key="FK_User_CompanyId"></key>
        <one-to-many class="User"></one-to-many>
    </set>
    <subclass name="Department" extends="Company" discriminator-value="Department">
        <many-to-one name="DepartmentParent" class="Company" column="DepartmentParentId" not-null ="false" foreign-key="FK_Department_DepartmentParentId" access="field.camelcase-underscore" />
    </subclass>
</class>

I do not have problem to eagerly load any of the association on the Company:

Session.Query<Company>().Where(c => c.Name == "Main Company").Fetch(c => c.Country).Single();
Session.Query<Company>().Where(c => c.Name == "Main Company").FetchMany(c => c.Employees).Single();

Also, I could eagerly load not-polymorphic association on the department:

Session.Query<Department>().Where(d => d.Name == "Department 1").Fetch(d => d.DepartmentParent).Single();

But I get NullReferenceException when I try to eagerly load any of the polymorphic association (from the Department):

Assert.Throws<NullReferenceException>(() => Session.Query<Department>().Where(d => d.Name == "Department 1").Fetch(d => d.Country).Single());
Assert.Throws<NullReferenceException>(() => Session.Query<Department>().Where(d => d.Name == "Department 1").FetchMany(d => d.Employees).Single());

Am I doing something wrong or this is not supported yet?

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about linq-to-nhibernate