mattcole
mattcole

Reputation: 1229

Selecting a joined entity with an ICriteria in NHibernate

In HQL I can do something like this:

select roleHeldByOwner.TargetPerson
from Person roleOwner
join roleOwner.RolesOnPeople roleHeldByOwner
where roleOwner.Id = :roleOwnerId

How can I achieve the same thing in a Criteria query? Specifically selecting something that isn't the first entity in the from clause.

Upvotes: 0

Views: 253

Answers (1)

Stuart Childs
Stuart Childs

Reputation: 3305

You can join by creating sub-criteria and select scalar results with Projections. Your Criteria query might look something like:

session.CreateCriteria(typeof(Person))
    .Add(Restrictions.Eq("Id", roleOwnerId))
    .SetProjection(Projections.Property("TargetPerson"))
    .CreateCriteria("RolesOnPeople", JoinType.InnerJoin) // Or LeftOuterJoin, etc.
    .List();

If you need multiple projections, use a ProjectionList like:

.SetProjection(Projections.ProjectionList()
    .Add(Projections.Property("...", ...))
    .Add(...)
    ...
)

I'm not sure what your domain looks like or what you're trying to get out of the query so the above may not be exactly correct. However, it should be what you need to get started.

Upvotes: 1

Related Questions