【问题标题】:Parameterizing a HQL IN clause using HqlBasedQuery?使用 HqlBasedQuery 参数化 HQL IN 子句?
【发布时间】:2010-03-05 15:55:15
【问题描述】:

如何为 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, 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 做到这一点。这就是为什么我让标题如此相似。

【问题讨论】:

  • ICriteria 非常适合这种情况。见 Restrictions.In()

标签: c# nhibernate hql castle-activerecord


【解决方案1】:

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

【讨论】:

  • 谢谢!这正是我想要的。
  • 您的链接已损坏
  • @MarcusAbrahão 请在 archive.org 中查找并编辑答案
猜你喜欢
  • 2010-09-25
  • 1970-01-01
相关资源
最近更新 更多