Frage

I'm doing a basic NHibernate query and want to add a possible 'Where' clause which may have several filters or none at all.

However, based on the users selection there may be several or nothing to filter on, ie returning all. Is there is a way to conditionally add the where clause and omit it when there's nothing to filter by?

So Im basically unsure how to add several or zero where clauses using QueryOver.

Thanks.

War es hilfreich?

Lösung

You can make use of the

 Restrictions.Conjunction()

As an example:

private IQueryOver<CustomerEntity> QueryForCustomer(int? companyCode, int[] zipCodes)
{        
    var customerRestritcions = Restrictions.Conjunction();
    if (companyCode.HasValue)
    {
        customerRestritcions.Add(Restrictions.Eq(Projections.Property<CustomerEntity>(c => c.CompanyCodeId), companyCode));
    }

    if (zipCodes != null)
    {
        customerRestritcions.Add(Restrictions.In(Projections.Property<CustomerEntity>(c => c.ZipCode), zipCodes));
    }

    return Session.QueryOver<CustomerEntity>(() => customer)
        .Where(customerRestriction)         
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top