3

我正在尝试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是一个字符串,因此数据库无法解释它的数字。我也尝试添加整数列表作为参数,但 NHibernate 不知道如何处理它。

如何使用where in(collection)CreateSQLQuery?

4

2 回答 2

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();
}
于 2012-08-22T08:36:07.350 回答
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)更好:)

问候

于 2012-08-22T13:48:13.303 回答