NHibernate query CreateCriteria

Jacob picture Jacob · Apr 14, 2010 · Viewed 7.7k times · Source

Is it possible to chose what columns I want in return from Session.CreateCriteria() ?

egz.:

var x = session.CreateCriteria();
    x.CreateAlias("EmployeePosition", "employeePosition");
    x.Add(Restrictions.Eq("employeePosition.Name", "Developer"));

and is there a way to add something like "select LastName" to avoid downloading the whole row.

Answer

mhanney picture mhanney · Apr 14, 2010

make a class that has only the properties you need, often this is a summary class like {Id, Label} and you'd reuse it anywhere you need a simple type, in a listing for example. Use ProjectionList to define which columns to return. Then use Transformers.AliasToBean to transform the result to your simple type.

ProjectionList projectionList = Projections.ProjectionList();
projectionList.Add(Projections.Property("EmployeeID"), "Id");
projectionList.Add(Projections.Property("EmployeePosition"), "Label");
var x = DetachedCriteria.For(Employee);
x.SetProjection(projectionList);
x.SetResultTransformer(Transformers.AliasToBean(SimpleType)));
return x.GetExecutableCriteria(UnitOfWork.CurrentSession).List<SimpleType>();