Creating NHibernate Linq Query from Criteria

I just added this gem to NHibernate.Linq (of the NHContrib variety – not to be confused with that other one). I’ll let the test speak for itself:

public void can_create_linq_query_from_arbitrary_criteria_query()
    var criteria = session.CreateCriteria<User>();
    criteria.Add(Restrictions.Le("RegisteredAt", new DateTime(2000, 1, 1)));

    var query = session.Linq<User>(criteria)
        .Where(u => u.Name == "nhibernate" || u.Name == "ayende");

    var list = query.ToList();
    Assert.AreEqual(1, list.Count);
    Assert.AreEqual("nhibernate", list.Single().Name);

My specific reason for adding this has to do with a custom ICriterion (more on that later) I needed to use in one of our criteria queries that I wanted to expose as an IQueryable. This method of being able to build a linq query from an arbitrary criteria seemed to solve my problem rather elegantly.

Let me know if you think this is crazy or if you like.

As of now, it is available in the trunk r1099.

👋 Hi! I’m Chad. I’m a Tech Lead turned founder, but I mostly see myself as a web developer specializing in the .NET Core, React, and Node.js ecosystems. I like to build tools to make developers’ lives easier. I am currently working on a modern job platform for .NET Core and Node.js.


What is this?


  1. Ivan

    I like it. Just have to test it if it works.

  2. Jindra

    we have integrated an NHibernate into our application but NHibernate.Linq doesn't seem to support the version. I have read somewhere that NHibernate.Linq features are contained in NHibernate self in the version but I am missing the described feature, which I really like. Do you know where it disappeared in the new version of NHibernate?

    1. Chad Lee
      Chad Lee

      The linq provider built into NHibernate 3 is based off of HQL rather than the Criteria API and does not support this.

    2. Jindra

      Thank you for your time and answer. As I have read today the Criteria is translated directly into SQL when used as a query. It makes sense now that the way I described is not supported. But I am not sure from your answer whether it is possible to create IQueryable from HQL. I.e. specify complex query using HQL and create a IQueryable which is already limited by this HQL query. Is it possible?