views:

63

answers:

2

I'm using NHibernate to load some objects into my ASP.NET MVC application.

For example, a submission is submitted by a user, and I want to display the username (but only the username) of a user, like this:

<%= Html.Encode(item.User.UserName) %>

When I load a submission using NHibernate, the User is lazy-loaded from the database, which means that the actual SQL query (to load user information) will only be generated and executed when I call the above line of code (which is what I want).

The problem is that the SQL query also selects other information about the user, like it's password, email, etc. This information is obviously not needed and is discarded.

The SQL query looks like this :

SELECT id, username, password, email FROM User WHERE Id = 1;

I conclude that NHibernate only lazy-load references to other objects that are mapped to tables in my database. It does not seem to lazy-load basic, primitive types like strings, ints, etc.

Can I do that? When the above line a code is selected, I would like the SQL query look something like this:

SELECT username FROM User WHERE Id = 1;

Is this possible? How?

A: 

You'll need to use a resultTransformer to map the query result to the object you want to store it (which I understand is your normal User DTO class but minus all the other fields)

Check this out http://docs.jboss.org/hibernate/stable/core/reference/en/html/querysql.html (its Hibernate, not NHibernate, but it should still apply) specifically section 16.1.5

Arthur C
+1  A: 

Is there a reason you don't want to load the complete object? Except in rare cases, there's no real performance difference.

I can understand not wanting to load the password into memory, although it should be encrypted and probably shouldn't be in your domain model anyway. What I would do in your case is subclass User into two classes, User and UserProfile (containing the password, etc.), so that you only work with the UserProfile object when you are managing the user account.

Jamie Ide