Quantcast
Channel: Development With A Dot
Viewing all articles
Browse latest Browse all 404

Delete By Id in NHibernate

$
0
0

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:publicstatic 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:publicstatic 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.


Viewing all articles
Browse latest Browse all 404

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>