使用 HqlBasedQuery 参数化 HQL IN 子句?
如何在 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 上执行此操作的类似问题:参数化 SQL IN 子句< /a> 这基本上是同一个问题,我只是想知道如何从 HQL 中做到这一点。这就是为什么我让标题如此相似。
How do you pass a list of things for the 'in' clause in Nhibernate HQL?
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);
Now, this isn't going to work, as much as I wish it would! Am I really stuck doing something like this:
// 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);
That's just ugly and I've tried to make it as not ugly and short as I can. If anyone has a nice way of accomplishing this please let me know.
Also I see Jeff asked a similar questions about how to do this on SQL: Parameterize an SQL IN clause
This is basically the same question I just want to know how to do it from HQL. That's why I'm making the titles so similar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
SetParameterList()
。来自 billsternberger 的代码片段.net:
Use
SetParameterList()
.Code snippet from billsternberger.net: