gpt4 book ai didi

c# - 使用 HqlBasedQuery 参数化 HQL IN 子句?

转载 作者:太空狗 更新时间:2023-10-29 21:25:33 24 4
gpt4 key购买 nike

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

最佳答案

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

关于c# - 使用 HqlBasedQuery 参数化 HQL IN 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2388021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com