使用HqlBasedQuery参数化HQL IN子句?

时间:2010-03-05 15:55:16

标签: c# nhibernate hql castle-activerecord

如何传递Nhibernate HQL中'in'子句的列表?

e.g。

// 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, 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);

那只是丑陋而且我试图让它尽可能不丑陋。如果有人有一个很好的方法来完成这个,请告诉我。

此外,我看到Jeff在SQL上提出了类似的问题:Parameterize an SQL IN clause 这基本上是同样的问题我只想知道如何从HQL中做到这一点。这就是为什么我让这些头衔如此相似。

1 个答案:

答案 0 :(得分:8)

使用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();