Colin Ramsay
Colin Ramsay

Reputation: 16477

NHibernate Reusable QueryOver

To keep my queries self-contained and potentially reusable, I tended to do this in NH2:

public class FeaturedCarFinder : DetachedCriteria
{
    public FeaturedCarFinder(int maxResults) : base(typeof(Car))
    {
        Add(Restrictions.Eq("IsFeatured", true));
        SetMaxResults(maxResults);
        SetProjection(BuildProjections());
        SetResultTransformer(typeof(CarViewModelMessage));
    }
}

I'd like to use QueryOver now that I've moved to NH3, but I'm not sure how to do the above using QueryOver?

Upvotes: 4

Views: 1504

Answers (1)

Colin Ramsay
Colin Ramsay

Reputation: 16477

Someone on the NH Users list gave me the answer:

public class FeaturedCarFinder : QueryOver<Car, Car> 
{ 
    public FeaturedCarFinder(int maxResults) 
    { 
        Where(c => c.IsFeatured); 
        Take(maxResults); 
        BuildProjections(); 
        TransformUsing(Transformers.AliasToBean(typeof(CarViewModelMessage))); 
    } 
    private void BuildProjections() 
    { 
        SelectList(l => 
            l.Select(c => c.IsFeatured) 
            //... 
            ); 
    } 
} 

Very similar to using DetachedCriteria as a base class, but note the use of QueryOver (i.e. the two type-argument version) rather than just QueryOver as the base class.

Upvotes: 6

Related Questions