Search code examples
nhibernatenhibernate-criteria

How to query a foreign key column with NHibernate, without retrieving the related entity


Say I have two classes: Parent and Child. A Parent has a property Children, which is of course a collection of Child objects.

Child doesn't have a ParentId property. It does have a Parent property.

So, my NHibernate mapping for Child includes:

<many-to-one name="Parent" class="Parent" column="ParentId" cascade="save-update" />

And my Parent mapping includes:

<bag name="children" access="field" inverse="true" cascade="all-delete-orphan">
    <key column="ParentId" />
    <one-to-many class="Child" />
</bag>

Now here's what I want to do: I want to get all the Child objects with a certain ParentId. I know I can first get the Parent and then return its Children property. But what if I'd want to query the Child table directly?

If it would be a mapped property (for example, Name), I could use NHibernate's criteria, but in this case, ParentId isn't mapped.

I tried using something like:

criteria.Add(Restrictions.Eq("Parent.Id", 1));

But that doesn't work. I resorted to using SQLCriterion (as explained here), but a friend/colleague got me thinking there must be a better way.

Any ideas? Something with projections and Restrictions.EqProperty?


Solution

  • I've done this using query over. Here is an example:

    Child foundChild = 
        session.QueryOver<Child>()
            .Where(x => x.Parent.Id == 1234).SingleOrDefault<Child>();