Вопрос

Is it possible to add where clauses dynamically to an NHibernate Query?

I have a collection of Clauses I need to Loop through and add a Where clause if required - i.e. if the user has entered multiple search criteria.

I Can write single queries, no problem, like this: get All Names beginning with 'a':

IEnumerable<Customer> customers = nHibernateSession.Query<Customer>().Where(x => x.Name.StartsWith("a")).ToList();

but I do not know how to then Add another where clause to this Effectively I need something that is like this:

foreach (clauses in SelectionClauses)
{
    //add a .Where(Clause) to The Session.Query
}

I suspect That The nHibernateSession.Query cannot be used this way... Does anyone know How to do this?

Это было полезно?

Решение

You can do this with the Linq provider (session.Query) by doing something like:

var query = session.Query<MyClass>();

foreach(var clause in clauses)
    query = query.Where(clause.BuildExpression());

Where BuildExpression returns Expression> for example

However this can get painful if you are using string name for your properties, and it will be a lot easier to achieve your result using session.QueryOver or session.CreateCriteria both of which support querying properties by their name instead of via expressions.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top