Ayende @ Rahien

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

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 5,953 | Comments: 44,409

filter by tags archive

Underused NHibernate Feature: Creating Objects In The Select Clause


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:

[TestFixture]

public class QueryThatCreatesAnObject

{  

    [Test]

    public void CheckCreatingObjectsInSelectClause()

    {

        ISessionFactory factory = DatabaseTests.CreateSessionFactory();

        ISession session = factory.OpenSession();

   

        session.Delete("from Blog");

        session.Flush();

 

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

        session.Save(blog);

        session.Flush();

 

        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.


Comments

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

No future posts left, oh my!

RECENT SERIES

  1. The RavenDB Comic Strip (3):
    28 May 2015 - Part III – High availability & sleeping soundly
  2. Special Offer (2):
    27 May 2015 - 29% discount for all our products
  3. RavenDB Sharding (3):
    22 May 2015 - Adding a new shard to an existing cluster, splitting the shard
  4. Challenge (45):
    28 Apr 2015 - What is the meaning of this change?
  5. Interview question (2):
    30 Mar 2015 - fix the index
View all series

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats