Question

I'm looking for an NHibernate criterion which does not add a restriction to a criteria. The reason for this is that I have a method which converts some input parameters into a criterion which is added to a criteria. There is a constellation of the input parameters where no restriction needs to by applied. Therefore I want to return some kind of dummy criterion.

Is there something like that in NHibernate?

Best Regards,
Oliver Hanappi

Was it helpful?

Solution

well you could do something like Restrictions.IsNotNull("id") if querying against an entity with 'id' being a primary key (and so can never be null). Anything that evaluates to no logical restriction can be used based on your requirements.

OTHER TIPS

You can use an empty Conjuction which is always true (it resolves to "1 = 1").

eg.

ICriterion conditionalCriteria = includeCriteria 
    ? Restrictions.Eq("someEntity.Field", variable)
    : (ICriterion) Restrictions.Conjuction();

var query = Session
    .CreateCriteria<SomeEntity>("someEntity")
    .Add(conditionalCriteria)
    .SetResultTransformer(Transformers.AliasToBean<SomeEntity>())
    .List<SomeEntity>();

You can add criteria as needed so just check your parameters for being null, if they are not null then add the criteria. See example:

Criteria cr = session.createCriteria(Employee.class)
cr.add(Restrictions.like("firstName", "Bob%"));

if (par_salary.IsNotNullOrEmpty())
{
     cr.add(Restrictions.eq("salary", par_salary));
}
List results = cr.list();

part of this taken from Hibernate Criteria Queries

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