简体   繁体   中英

Does anyone know how to translate LINQ Expression to NHibernate HQL statement? 2nd edition

Time to go round 2 with this question ( link ) since it still seems to generate a lot of traffic without having a actual answer. The question was asked 5 years ago while NHibernate got up from version 2.1 to 4.0 (as per August 17th) during that time. I'm currently stuck with this issue too, so there it goes.

Currently, the way I solved it in my project for a simple case is by this extension method:

public static void DeleteByKey<TEntity, TKey>(this ISession session, TKey key)
   where TEntity : class
   {
      var metadata = session.SessionFactory.GetClassMetadata(typeof (TEntity));
      var hql = String.Format("delete {0} where id = :id", metadata.EntityName);
      var results = session.CreateQuery(hql).SetParameter("id", key).ExecuteUpdate();

      if (results != 1)
         throw new EntityNotFoundException();
   }

This is however weakly typed and only works with a key, not a general LINQ expression predicate.

Not easy to do, I'm afraid. There is an open request for that (by myself) in NHibernate: Strongly Typed Deletes . I believe that for now your solution is the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM