Question

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);
    }
Was it helpful?

Solution 3

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

OTHER TIPS

If you mapped the UserId property as "Id" in your mapping file (which you probably do if you used the same conventions as in this question), it should be:

.Add(Expression.Eq("user.Id", userId))

The Id property is a special case in NHibernate

why don't you create an alias for UserPublications and add the expression there? like

.CreateCriteria("UserPublications", "up")                    
.Add(Expression.Eq("up.ClientUser.UserId", userId));

or maybe

.CreateCriteria("UserPublications", "up")                    
.CreateAlias("up.ClientUser", "user")
.Add(Expression.Eq("user.UserId", userId));

as far as i can see calling

.CreateAlias("ClientUser", "user")

depends on NH's ability to detect where ClientUser exists and create the join which may not be working (bug or otherwise)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top