I'm trying to limit the number of entities that an NHibernate Criteria will return. The standard seems to be to use SetMaxResults, but this doesn't work properly if my Criteria involves a LEFT OUTER JOIN on a many-to-many relationship.
An example:
Dogs have owners (a many-to-many relationship), and I need to retrieve up to 10 dogs that belong to some set of owners. Doing
session.CreateCriteria<Dog>()
.CreateAlias("Owners", "Owners")
.Add(Restrictions.In("Owners.Id", idCollection)
.SetMaxResults(10)
.List<Dog>();
will translate into a SQL query like
SELECT TOP(10) * FROM DOGS d
LEFT OUTER JOIN OWNERS_DOGS od ON d.id = od.id
WHERE od.OWNER_ID IN (:valueone, :valuetwo)
My TOP restriction is happening too early, causing a dog with multiple owners that match the criteria to count multiple times towards my limit of 10. Is there a clean way to tell NHibernate that I only want it to hydrate the first X dog objects? I probably won't be able to get out of performing a full SELECT on the database, but it would be nice if I could avoid loading up every dog in the system, since I'm only going to be displaying 10 of them.