tags:

views:

668

answers:

2

I need to return a constant from an HQL query in NHIbernate

SELECT new NDI.SomeQueryItem(user, account, " + someNumber + ") 
FROM NDI.SomeObject object

I am trying for something like above. I've tried this:

SELECT new NDI.SomeQueryItem(user, account, :someNumber) 
FROM NDI.SomeObject object

And then later:

.SetParameter("someNumber", 1).List<SomeQueryItem>();

But in the first case I get a 'Undefined alias or unknown mapping 1'. Which makes some sense since it probably thinks the 1 is an alias.

For the second I get a 'Undefined alias or unknown mapping :someNumber' which again makes some sense if it never set the parameter.

I have to believe there's some way to do this.

+1  A: 

Please feel free to continue to believe there is some way to do this - but with HQL there isn't!

Why would you want to anyway? If you want to update the value this property to the value you specify, then do so after you've loaded the objects. Alternatively, if your result set doesn't quite match to your objects, you could alway use a SQL query (which you can still do via an NHibernate session). But the purpose of NHibernate is to map what's in your database onto objects, so specifying a manual override like this is quite rightly not allowed.

David M
"NHibernate is to map what's in your database onto objects" Fair point, problem is this value based on values outside of the database and the item's constructor has logic based off the value. It's almost like relay information using the query. I won't argue right or wrong on this...
Programmin Tool
The item can't afford to have constructor logic like this if it's an NHibernate object - this stops it being the sort of POCO that NHibernate is designed to work with.
David M
I hate that you're spot on about this. I think this question could be marked off as intellectual suicide... public and brutal.
Programmin Tool
Sorry to dash your hopes. You could try an intermediate layer of objects, retrieving a list of POCOs from NHibernate then doing a .ConvertAll with the delegate instantiating your own objects with the value passed through? JUst a thought.
David M
+1  A: 

It sounds like there is a (small?) disconnect between your domain objects and your database model. What about creating a small "DTO" object to bridge this gap?

Have your query return a list of SomeQueryItemDTO (or whatever you want to call it) which, due to the naming, you know is not a true part of your domain. Then have some function to process the list and build a list of true SomeQueryItem objects by incorporating the data that is extraneous to the database.

If you're already using the Repository Pattern, this should be easier since all the ugly details are hidden inside of your repository.

Stuart Childs