Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 6,007 | Comments: 44,761

filter by tags archive

Underused NHibernate Feature: Creating Objects In The Select Clause

time to read 9 min | 1716 words

I got a comment today from Jim Bolla asking about this query:

select new Address(c.Address, c.City, C.Zip) from Customer c

His comment was:

I've been using NHibernate for at least 6 months now and haven't heard of this feature. Does this really work? What are the requirements/limitations? Is this in the documentation? Or even in the example code/tests?

As he didn't leave an email or another way to contant him, I'm going to broadcast the reply to the world, hoping it would get back to him. (As an aside, if you ask a question, I need a way to get back to you, so leave a way to do so).

First, it is a documented feature that you're welcome to use. It's not used much (and sadly I couldn't find a test for it after a quick grepping), mainly because it is obscure. I just gave it a quick test, and it is working correctly. One word of caution. you need ot make sure that you imported the type that you are trying to create. Here is the sample test:


public class QueryThatCreatesAnObject



    public void CheckCreatingObjectsInSelectClause()


        ISessionFactory factory = DatabaseTests.CreateSessionFactory();

        ISession session = factory.OpenSession();


        session.Delete("from Blog");



        Blog blog = new Blog("ayende @ blog");




        IList list = session.Find(@"select

                    new System.Collections.DictionaryEntry(b.BlogID, b.BlogName)

                    from Blog b");

        Assert.AreEqual(1, list.Count);


        DictionaryEntry de = (DictionaryEntry)list[0];

        Assert.AreEqual(de.Key, blog.BlogID);

        Assert.AreEqual(de.Value, blog.BlogName);



As you can see, it's pretty slick. I'm not 100% about how you import a class, and I don't have the time to investigate, but the documentation for that is here.


Comment preview

Comments have been closed on this topic.


No future posts left, oh my!


  1. Speaking (3):
    23 Sep 2015 - Build Stuff 2015 (Lithuania & Ukraine), Nov 18 - 24
  2. Production postmortem (11):
    22 Sep 2015 - The case of the Unicode Poo
  3. Technical observations from my wife (2):
    15 Sep 2015 - Disk speeds
  4. Find the bug (5):
    11 Sep 2015 - The concurrent memory buster
  5. Buffer allocation strategies (3):
    09 Sep 2015 - Bad usage patterns
View all series



Main feed Feed Stats
Comments feed   Comments Feed Stats