使用Nhibernate和参数删除

时间:2016-09-13 13:18:10

标签: sql nhibernate

我需要执行一个删除记录的查询,如下所示:

DELETE FROM News WHERE DateRelease <= DATEADD(DAY, -60, GETDATE())

这是我的代码

public void Removehistory(Int32 daysToKeepFromNow)
{
    using (ISession session = NHibernateHelper.OpenSession())
    {
        session.Delete("DELETE FROM News WHERE DateRelease <= DATEADD(DAY, -" + daysToKeepFromNow + ", GETDATE())");
    }
}

但发出此错误:

  

不支持DML操作[DELETE FROM News WHERE DateRelease   &lt; = DATEADD(DAY,-60,GETDATE())]

我对nhibernate很新,这个查询出了什么问题?

1 个答案:

答案 0 :(得分:1)

因为session.Delete不是运行查询的方法:Hybernate Session

您应该使用session.createQuery然后使用query.executeUpdate

Query query = session.createQuery("delete News where DateRelease <= (sysdate -60)");

int result = query.executeUpdate();

if (result > 0) {
    System.out.println("Old news removed");
}