문제

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.

도움이 되었습니까?

해결책

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)         
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top