How can one delete NHibernate objects using a criteria?

前端 未结 4 1363
旧巷少年郎
旧巷少年郎 2020-12-15 23:28

This must be a simple question. Given a criteria, how one deletes the entities satisfying the criteria?

The rationale:

HQL and NH criteria

4条回答
  •  鱼传尺愫
    2020-12-16 00:11

    You may use the criteria to select the IDs of your elements, join them in a string and use HQL to delete them?

    Something like:

    public void Delete(ICriteria criteria, string keyName, string tableName)
    {
        criteria.setProjection(Projections.Attribute(keyName));
        IList itemIds = criteria.List();
    
        string collection = string.Join(",", Array.ConvertAll(itemIds, Convert.ToString));
    
        Session.HQL(string.Format("delete from {0} where {1} in ({2})", tableName, keyName, collection);
    }
    

    This code was not tested or compiled (in particular I'm not sure of the HQL section), but I think that you got the idea: we don't fetch the whole objects thanks to the projection, but only the indices.

提交回复
热议问题