Delete By Id in NHibernate

NHibernate allows executable queries, that is, plain old UPDATEs, INSERTs and DELETEs. This is great, for example, for deleting an entity by its id without actually loading it. Note, that the following won’t give you that:

   1: session.Delete(session.Load<TEntity>(id));

NHibernate will load the proxy before it actually deletes it. But the following does work perfectly:

   1: public static Boolean DeleteById(this ISession session, Type entityType, Object id)
   2: {
   3:     var metadata = session.SessionFactory.GetClassMetadata(entityType);
   4:  
   5:     var hql = String.Format("delete {0} where id = :id", metadata.EntityName);
   6:  
   7:     var results = session.CreateQuery(hql).SetParameter("id", id).ExecuteUpdate();
   8:  
   9:     return (results == 1);
  10: }
  11:  
  12: public static Boolean DeleteById<T>(this ISession session, Object id)
  13: {
  14:     return (DeleteById(session, typeof(T), id));
  15: }

A single DELETE SQL command is sent to the database with this approach.

                             

1 Comment

Comments have been disabled for this content.