问题
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