Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
Peter Avatar asked Dec 21 '22 03:12

Peter


1 Answers

You have to alias the association path. This will return a proxy for Parent assuming that are using lazy loads. You can access the parent's Id property without triggering a load.

return _session.CreateCriteria<Child>()
    .CreateAlias("Parent", "parent")
    .Add(Restrictions.Eq("parent.Id", parentId))
    .List<Child>();
like image 116
Jamie Ide Avatar answered Apr 08 '23 10:04

Jamie Ide