NHibernate Projections to retrieve a Collection?

我与影子孤独终老i 提交于 2019-12-11 16:41:59

问题


I´m having some trouble retrieving a collection of strings in a projection: say that I have the following classes

public class WorkSet {
    public Guid Id { get; set; }
    public string Title { get; set; }
    public ISet<string> PartTitles { get; protected set; }
}
public class Work {
    public Guid Id { get; set; }
    public WorkSet WorkSet { get; set; }
    //a bunch of other properties
}

I then have a list of Work ids I want to retrieve WorkSet.Title, WorkSet.PartTitles and Id for.

My tought was to do something like this:

            var works = Session.CreateCriteria<Work>()
            .Add(Restrictions.In("Id", hitIds))
            .CreateAlias("WorkSet", "WorkSet")
            .SetProjection(
            Projections.ProjectionList()
                .Add(Projections.Id())
                .Add(Projections.Property("WorkSet.Title"))
                .Add(Projections.Property("WorkSet.PartTitles")))
            .List();

The Id and Title loads up just fine, but the PartTitles returns null. Suggestions please!


回答1:


This might not work using criteria. Most probably, it is because the set can not be retrieved by the same sql query that is generated by the criteria.

I would actually really consider to retrieve the whole object. It is much easier and if it is not a very very special case, it is not worth the troubles. (By the way, it could be faster to retrieve whole objects, the may be already in the cache.) What usually counts is the number of queries (and its complexity of course), not the number of columns retrieved.

It probably works with HQL, there is a elements function there. Consider to use HQL for static queries anyway, it is more powerful.

select 
  ws.Title, 
  elements(ws.PartTitles), 
  w.id
from 
  Work w 
  inner join w.WorkSet ws
where w.id in (:ids)

elements is allowed in the select clause, but I don't know what you'll get. You most probably get as many records as there are PartTitles in the result, because there is only one SQL statement built.



来源:https://stackoverflow.com/questions/2621826/nhibernate-projections-to-retrieve-a-collection

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