Ras Ras - 2 months ago 31
SQL Question

Delete with Nhibernate and parameters

I need to execute a query that delete the records as follow:

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


This is my code

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


but fire this error: Not supported for DML operations [DELETE FROM News WHERE DateRelease <= DATEADD(DAY, -60, GETDATE())]

I am pretty new to nhibernate, what's wrong with this query?

Answer

because session.Delete is not a method to run queries: Hybernate Session

you should instead use session.createQuery and then 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");
}
Comments