你如何传递Nhibernate HQL中’in’子句的列表?
例如
// 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);
现在,这不会起作用,就像我希望的那样!我真的坚持做这样的事情:
// data input from the user interface,... }; 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),productIds) ActiveRecordMediator.ExecuteQuery(query);
那只是丑陋而且我试图让它尽可能不丑陋.如果有人有一个很好的方法来完成这个,请告诉我.
另外我看到杰夫在sql上问了一个关于如何做到这一点的类似问题:Parameterize an SQL IN clause
这基本上是同样的问题我只想知道如何从HQL中做到这一点.这就是为什么我让这些头衔如此相似.
解决方法
使用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();