2010-03-05 14 views
6

¿Cómo se pasa una lista de cosas para la cláusula 'in' en Nhibernate HQL?Parametrizar una cláusula HQL IN utilizando HqlBasedQuery?

p. Ej.

// data input from the user interface, not known at compile time 
object[] productIds = {1, 17, 36, ... }; 
string hqlQuery = @" 
       from Product as prod 
       where prod.Id in (?)"; 
HqlBasedQuery query = new HqlBasedQuery(typeof(Product), hqlQuery, productIds) 
ActiveRecordMediator.ExecuteQuery(query); 

¡Ahora, esto no va a funcionar, tanto como desearía! Estoy realmente atascado haciendo algo como esto:

// data input from the user interface, not known at compile time 
object[] productIds = {1, 17, 36, ... }; 
string hqlQuery = @" 
       from Product as prod 
       where prod.Id in ({0})"; 

// build string array of the right number of '?' characters 
string[] paramStringArray = new String('?', productIds.Length).ToCharArray().Select(item => item.ToString()).ToArray(); 
// join to make '?, ?, ?, ?, ?' 
string parameterString = string.Join(", ", paramStringArray); 
hqlQuery = string.Format(hqlQuery , parameterString); 

HqlBasedQuery query = new HqlBasedQuery(typeof(Product), hqlQuery, productIds) 
ActiveRecordMediator.ExecuteQuery(query); 

Eso es sólo feo y lo he intentado que sea lo más corto y no fea como pueda. Si alguien tiene una buena manera de lograr esto, por favor hágamelo saber.

También veo Jeff hizo unas preguntas similares acerca de cómo hacer esto en SQL: Parameterize an SQL IN clause Esta es básicamente la misma pregunta que sólo quiero saber cómo hacerlo de HQL. Es por eso que estoy haciendo que los títulos sean tan similares.

+0

ICriteria es muy adecuado para esto. vea Restrictions.In() – dotjoe

Respuesta

8

Use SetParameterList().

Code snippet from billsternberger.net:

ArrayList stateslist = new ArrayList(); 
stateslist.Add("TX"); 
stateslist.Add("VA"); 

string hql = String.Format("FROM Contact c where State in (:states)"); 
SimpleQuery<Contact> q = new SimpleQuery<Contact>(hql); 
q.SetParameterList("states", stateslist); 

Contact[] result = q.Execute(); 
+0

¡Gracias! Eso es exactamente lo que estaba buscando. –

+0

+1 esta es la forma correcta y funciona como se esperaba. – Jaguar

+0

Tiene un enlace roto –

Cuestiones relacionadas