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:
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();
Blog blog = new Blog("ayende @ blog");
IList list = session.Find(@"select
new System.Collections.DictionaryEntry(b.BlogID, b.BlogName)
from Blog b");
DictionaryEntry de = (DictionaryEntry)list;
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.