如何使用NHibernate Projections检索集合

我懒得加载集合,还因为person表中有这么多字段,我正在编写一个投影函数来检索某些属性。 它适用于属性,而不适用于其他实体的集合。 如果它们作为代理加载我会很好,我可以稍后得到它们,但现在它只是加载null。

public IList ListTop40() { var list = _session.CreateCriteria(typeof(Person)) .SetProjection(Projections.ProjectionList() .Add(Projections.Property("FirstName")) .Add(Projections.Property("LastName")) .Add(Projections.Property("Jersey")) .Add(Projections.Property("FortyYard")) .Add(Projections.Property("BenchReps")) .Add(Projections.Property("VertJump")) .Add(Projections.Property("ProShuttle")) .Add(Projections.Property("LongJump")) .Add(Projections.Property("PersonSchoolCollection")) ) .List() .Select(l => new Person() { FirstName = (string)l[0], LastName = (string)l[1], Jersey = (Decimal)l[2], FortyYard = (Decimal)l[3], BenchReps = (Decimal)l[4], VertJump = (Decimal)l[5], ProShuttle = (Decimal)l[6], LongJump = (Decimal)l[7], PersonSchoolCollection = (IList)l[8]}); IList s = list.ToList(); return s; } 

尝试使用AliasToBeanResultTransformer:

 var list = _session.CreateCriteria(typeof(Person)) .SetProjection(Projections.ProjectionList() .Add(Projections.Property("FirstName")) .Add(Projections.Property("LastName")) .Add(Projections.Property("Jersey")) .Add(Projections.Property("FortyYard")) .Add(Projections.Property("BenchReps")) .Add(Projections.Property("VertJump")) .Add(Projections.Property("ProShuttle")) .Add(Projections.Property("LongJump")) .Add(Projections.Property("PersonSchoolCollection")) ) .SetResultTransformer(new NHibernate.Transform.AliasToBeanResultTransformer(typeof(Person))) .List(); 

你有几个属性? 我在客户端实体上有大约30个或更多,在NH中加载时没有问题。

当情况不是这样时,你可能会担心性能问题。 (旧:过早优化是所有邪恶的根源“:))

话虽如此 – 我怀疑这样的事情得到了支持。