dragonfly
dragonfly

Reputation: 17773

How to merge two criterias / QueryObjects in NHibernate

I have a QueryObject object detached and I have a second ICriteria object criteria.

        ICriteria criteria = session.CreateCriteria<Theme>()
            .CreateAlias("InceptionCycle", "ic", JoinType.LeftOuterJoin)
            .CreateAlias("ClosingCycle", "cc", JoinType.LeftOuterJoin)
            .Add(Restrictions.Le("ic.CycleMonth", cycleDate))
            .Add(Restrictions.Or(
                Restrictions.IsNull("cc.ID"),
                Restrictions.Ge("cc.CycleMonth", cycleDate)));

        QueryOver<Theme, Theme> detached = new GlobalTheme().GetQuery();

        // and now how to make new query : detached AND criteria

Is it possible to merge/join/add AND condition between this two criteria objects? Something like this (of course following line of code doesn't work as Add method do not accept ICriteria type):

detached.DetachedCriteria.GetExecutableCriteria(session).Add(criteria).List<Theme>();

The reason why I want to achieve is:

As a result, in order to handle all combination of n possible criterias I would have to create at least n*n QueryObjects. If it's possible to AND two or more criterias, I have to create only n *QueryObject* types.

Thanks

Upvotes: 0

Views: 1111

Answers (1)

Diego Mijelshon
Diego Mijelshon

Reputation: 52745

It's not possible to "merge" criteria queries, but what you can do for reuse is create a method that adds whatever restrictions you want to the specified query.

A generic example, using an extension method:

var results = session.CreateCriteria<AnEntity>()
                     .Add(aSpecificRestriction)
                     .AddGenericFilters()
                     .List();

public void AddGenericFilters(this ICriteria criteria)
{
    criteria.Add(whatever);
    return criteria;
}

Upvotes: 1

Related Questions