I am having trouble getting my query by criteria to work.
I want to filter the UserPublications collection by userId but it is not filtering. The ClientPublications collection has filtered correctly though.
Any advice?
Thanks in advance.
public IList<ClientReport> GetAvailableClientReports(int userId)
{
ICriteria criteria = NHibernateSession.CreateCriteria(typeof(ClientReport))
.CreateCriteria("ClientPublications")
.Add(Expression.Eq("IsDownloaded", true))
.SetResultTransformer(CriteriaUtil.DistinctRootEntity)
.AddOrder(Order.Asc("Name"))
.CreateCriteria("UserPublications")
.CreateAlias("ClientUser", "user")
.Add(Expression.Eq("user.UserId", userId));
return GetByCriteria(criteria);
}
For future ref, I got it working by adding a filter in the mapping file
First define the filter in the parent class mapping:
<filter-def name="userFilter">
<filter-param name="userId" type="System.Int32"/>
</filter-def>
Then define filter further in the mapping to the collection
<bag name="UserPublications" access="property" lazy="true" cascade="all-delete-orphan">
<key column="ClientPublicationID"/>
<one-to-many class="ReportMgr.Model.ClientUserPublication, ReportMgr.Model" />
<filter name="userFilter" condition="ClientUserID = :userId"></filter>
</bag>
Then enable the filter and specify the parameter value just before executing the ICriteria query:
NHibernateSession.EnableFilter("userFilter").SetParameter("userId", userId);
ICriteria criteria = NHibernateSession.CreateCriteria(typeof(ClientReport))
.CreateCriteria("ClientPublications")
blah blah blah
return GetByCriteria(criteria);