我正在尝试使用where column in (collection)
使用以下方法从表中删除行:
public void DeleteRows(int parentId, List<int> years)
{
var yearsAsCommaSeperatedString = ListToCommaSeperatedString(years);
const string query = "DELETE FROM TABLE t WHERE t.PARENT_ID=:Parent AND t.YEAR in(:yearList)";
Session
.CreateSQLQuery(query)
.SetParameter("Parent", parentId)
.SetParameter("yearList", yearsAsCommaSeperatedString)
.ExecuteUpdate();
}
private static string ListToCommaSeperatedString(IEnumerable<int> ints)
{
var aggregate = ints.Aggregate("", (current, i) => current + (i + ", "));
return aggregate.Substring(0, aggregate.LastIndexOf(",", StringComparison.Ordinal));
}
问题是yearsAsCommaSeperatedString
是一个字符串,因此db无法解释数字。我也尝试添加整数列表作为参数,但NHibernate不知道如何处理它。
如何将where in(collection)
与CreateSQLQuery一起使用?
答案 0 :(得分:6)
你可以使用这样的东西
ISession session = GetSession();
string hql = @"from Product p
where p.Category in (:categories)";
var categoriesToSearch = new[] {new Category {Id = 1}, new Category {Id = 2}};
var query = session.CreateQuery(hql);
query.SetParameterList("categories", categoriesToSearch);
var products = query.List<Product>();
或者你可以试试这个
public void DeleteRows(int parentId, List<int> years)
{
const string query = "DELETE FROM TABLE t WHERE t.PARENT_ID=:Parent AND t.YEAR in (:yearList)";
Session
.CreateSQLQuery(query)
.SetParameter("Parent", parentId)
.SetParameterList("yearList", years)
.ExecuteUpdate();
}
答案 1 :(得分:1)
如果您的方法有效,您可以再次使用SetParamter,但必须将SQL-Query更改为以下内容:
var yearsAsCommaSeperatedString = ListToCommaSeperatedString(years);
const string query = "DELETE FROM TABLE t WHERE t.PARENT_ID=:Parent AND t.YEAR in(\":yearList\")";
Session .CreateSQLQuery(query)
.SetParameter("Parent", parentId)
.SetParameter("yearList", yearsAsCommaSeperatedString)
.ExecuteUpdate();
应该比字符串连接更好(sql-injection):)
问候
答案 2 :(得分:0)
我发现最简单的解决方案是将年份添加到sql字符串中,而不是将它们添加为参数。
const string query = "DELETE FROM TABLE t WHERE t.PARENT_ID=:Parent AND t.YEAR in(" + yearsAsCommaSeperatedString + ")";
请注意,这会使代码容易受到sql注入。