Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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.

Comments

Vladimir Moushkov said:

As many extension methods designs it has flaw. The bad thing about this is that it would work in certain cases. For example - the fluent nhibernate configuration will not be respected.

# January 11, 2014 11:42 AM

Ricardo Peres said:

Vladimir:

What do you mean by "the fluent nhibernate configuration will not be respected"?

# January 12, 2014 1:26 PM