NHibernate query CreateCriteria

懵懂的女人 提交于 2019-12-23 06:49:30

问题


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.


回答1:


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>();



回答2:


You can do this using Projections:

IList<Object[]> list = session.CreateCriteria(typeof(Employee))
  .SetProjection(Projections.ProjectionList()
    .Add(Projections.Property("FirstName"))
    .Add(Projections.Property("LastName"))
  ).List<Object[]>();

  foreach( Object[] person in list )
  {
    String firstName = person[0];
    String lastName = person[1];
  }

Check out the NHibernate.Expressions namespace for other Projections as well.




回答3:


I would suggest giving Linq to NHibernate a try. It will let you do what you are asking in a very natural way.




回答4:


To add to dana's answer, if you have an actual class you want to read it in to, you can also use Transformers.AliasToBean with the projection. NHibernate will then try to populate properties of the object with values from matching field names.



来源:https://stackoverflow.com/questions/2640777/nhibernate-query-createcriteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!