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?
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>();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With