1

我有这样的数据模型:

class Hand {
    public int id;
    ...
}
class Person {
    public int id;
    public string name;
    public IList<Hand> hands;
    ...
}

要从数据库中获取数据,我这样做:

ICriteria criteria = databaseSession.CreateCriteria(typeof(Person));

ProjectionList projections = Projections.ProjectionList();

projections
    .Add(Projections.Property("id").As("id"))
    .Add(Projections.Property("name").As("name"))
    .Add(Projections.Property("hands").As("hands"));

projections.Add(Projections.GroupProperty("id"));
projections.Add(Projections.Count("id"), "count");

criteria.SetProjection(projections);

criteria.SetResultTransformer(
    NHibernate.Transform.Transformers.AliasToBean(typeof(PersonDTO)));

但是 NHibernate 不会在 hands 属性中加载嵌套对象。它只是给出空值。谁能帮助我如何填充嵌套对象(超过一级深度)。使用预测而不是查询对我来说会更好。注意:在映射中不会有问题,因为当我加载没有任何投影的数据时,它工作得很好。

4

1 回答 1

1

一个可能的解决方案

var query = databaseSession.CreateCriteria(typeof(Person))
    .JoinAlias("hands", "hand")
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property("Id"))
        .Add(Projections.Property("Name"))
        .Add(Projections.Property("hand.Id"))
        .Add(Projections.Property("hand.Foo")))
    .List<object[]>()
    .GroupBy(arr => (int)arr[0])
    .Select(g => new PersonDTO
    {
        Id = g.Key,
        Name = g.First().Name,
        Hands = g.Select(arr => new Hand { Id = arr[2], Foo = arr[3] }).ToList(),
    });

var results = query.ToList();
于 2013-06-07T12:30:15.320 回答