简体   繁体   中英

How to use NHibernate Projections to retrieve a collection

I am lazy loading the collections, and also because there are so many fields within the person table, I am writing a projection function to retrieve only certain properties. It works with properties, just not collections of other entities. I would be fine if they were loaded in as proxies and i could get them later, but right now it just loads in null.

public IList<Person> 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<IList>()
                    .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<Person_School>)l[8]});

            IList<Person> s = list.ToList();
            return s;
        }

try using 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<Person>();

How many properties do you have ? I have around 30 maybe more on a Client entity and there's no problem when loading it in NH.

You might be worrying about performance when it's not really the case. (the old : premature optimization is the the root of all evil" :) )

Having that said - I doubt something like this is supported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM