Question

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?

Was it helpful?

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>();

OTHER TIPS

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>();

I think it can be done via Criteria like this:

criteria.Add(Restrictions.Eq("Parent", Session.Load<Parent>(1));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top