This is an example using projection:
List results = session.CreateCriteria<BrandTable>()
.SetProjection( Projections.ProjectionList()
.Add( Projections.Id(), "Id" )
.Add( Projections.Property("Name"), "Name" )
)
.SetResultTransformer(Transformers.AliasToBean<BrandTable>()); // edit - don't forget the result transformer!
.List();
here an example using QueryOver:
NHibernate QueryOver select entity and aggregates
[edit]
also, there is currently a bug when caching icriteria projections.
(if you try to cache the query, you get an exception)
https://nhibernate.jira.com/browse/NH-1090
[/edit]
Releted posts:
NHibernate Criteria: howto exclude certain mapped properties/collections?
Only retrieve specific columns when using Critera queries?
LINQ-NHibernate - Selecting only a few fields (including a Collection) for a complex object
to make your queries refactor-safe (no 'magic strings'), you can implement something like so:
public static class ObjectExtensions
{
public static string NameOf<T>(this T target, Expression<Func<T, object>> propertyExpression)
{
MemberExpression body = null;
if (propertyExpression.Body is UnaryExpression)
{
var unary = propertyExpression.Body as UnaryExpression;
if (unary.Operand is MemberExpression)
body = unary.Operand as MemberExpression;
}
else if (propertyExpression.Body is MemberExpression)
{
body = propertyExpression.Body as MemberExpression;
}
if (body == null)
throw new ArgumentException("'propertyExpression' should be a member expression");
// Extract the right part (after "=>")
var vmExpression = body.Expression as ConstantExpression;
// Extract the name of the property
return body.Member.Name;
}
}
using it like this:
MyEntity entity = null; // don't need a 'valid' instance.
string propName = entity.NameOf(x => x.SomePropertyName);