NHibernate - define la condición donde

In my application the user can defines search-conditions. He can choose a column, set an operator (equals, like, greater than, less or equal than, etc.) and give in the value. After the user clicks on a button and the application should do a search on the database with the condition. I use NHibernate and ask me now, what is the efficientest way to do this with NHibernate.

Should I create a query with it like (Column=Name, Operator=Like, Value=%John%)

        var a = session.CreateCriteria<Customer>();
        a.Add(Restrictions.Like("Name", "%John%"));
        return a.List<Customer>();

Or should I do this with HQL:

        var q = session.CreateQuery("from Customer where " + where);
        return q.List<Customer >();

Or is there a more bether solution?

Gracias por tu ayuda.

Best Regards, Thomas

preguntado el 09 de enero de 11 a las 12:01

I'm sure someone will help you if you accept peoples answers. -

Hi Phill - I have just no see, that I have to mark an answer accepted. Now I have do that for the other questions. I think, this will increase the accept-rate? - or is there more to do? Thanks! -

2 Respuestas

You can use either one of them. There might be hardly an differences between the two. But whatever you do make sure that your column names are in constants or are mapped to the column name otherwise your repository will be tightly coupled to your model definition i.e if you update the columnname you will have to go and update these statements yourself.

And when you are building the where clause makes ure you have a function that appends the right query. you will probably be having a switch case statement for the same.

Respondido el 09 de enero de 11 a las 15:01

In term of efficence there is no difference. In the HQL version I would prefer use a parameter instead of adding the where part as a string. If you are using NH3.0 you can consider using QueryOver too, to avoid using string to describe your properties

Respondido el 09 de enero de 11 a las 15:01

Hi Felice - how do you mean this "use a parameter"? Can I define a parameter for the whole where? - BennoDual

one more quesion about your answer: do you use NH3.0? - Is it official released now? Is there a big effort to update from 2.1 to 3.0? - BennoDual

You can write an hql say "where myprop=:p0" and then call SetParameter("p0",myval). This is always a good practice. For the NH3.0 question, yes it is official released, updating is not a big deal, but if I were you I will still wait for some bug fixing ;) - Felice Pollano

i would suggest you update.. there are some changes in NH3. It doesnt support Session.Linq anymore.. instead they hv introduced QueryOver which is pretty awesome.. try it.. - Baz1nga

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.