How to query a foreign key column with NHibernate without getting the associated object

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

Child does not have the ParentId property. It has the 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 is what I want to do: I want to get all Child objects with a specific ParentId . I know that I can get Parent first and then return its Children property. But what if I want to directly query the Child table?

If this is a display property (e.g. Name ), I can use NHibernate criteria, but in this case, ParentId not displayed.

I tried using something like:

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

But that does not work. I resorted to using SQLCriterion (as explained here ), but a friend / colleague made me think that there should be a better way.

Any ideas? Something with projections and Restrictions.EqProperty ?

+4
source share
3 answers

I did this using a request. Here is an example:

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

You must specify an association path. This will return the proxy for the intended parent who is using lazy loads. You can access the property of the parent identifier without starting the download.

 return _session.CreateCriteria<Child>() .CreateAlias("Parent", "parent") .Add(Restrictions.Eq("parent.Id", parentId)) .List<Child>(); 
+6
source

I think this can be done using the following criteria:

 criteria.Add(Restrictions.Eq("Parent", Session.Load<Parent>(1)); 
0
source

Source: https://habr.com/ru/post/1390279/


All Articles