Search code examples
nhibernateprojectionqueryover

Nhibernate queryover projection on detail entity fields


What I want to do is to be able to use projections with queryover. I have succeeded doing this using projections on first level only using AliasToBean Transformer but when i project on properties from a detail class nhibenate throws the following exception:

 Could not find a setter for property 'FirstContact' in class 'Model.Personnel.Entities.Employee'
 at NHibernate.Properties.ChainedPropertyAccessor.GetSetter(Type theClass, String propertyName)
 at NHibernate.Transform.AliasToBeanResultTransformer.TransformTuple(Object[] tuple, String[] aliases)
 at NHibernate.Loader.Criteria.CriteriaLoader.GetResultList(IList results, IResultTransformer customResultTransformer)
 at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
 at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
 at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor session)
 at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
 at NHibernate.Impl.CriteriaImpl.List(IList results)
 at NHibernate.Impl.CriteriaImpl.List[T]()
 at NHibernate.Criterion.QueryOver`1.List[U]()
 at NHibernate.Criterion.QueryOver`1.NHibernate.IQueryOver<TRoot>.List[U]()
 at Tests.Entities.EmployeeFacts.QueryEmployees()

This is my current code:

Employee anEmployee = null;
Contact aContact = null;

session.QueryOver(() => anEmployee).Left
                .JoinAlias(() => anEmployee.Contact, () => aContact)
                .OrderBy(() => aGender.Name).Asc
                .ThenBy(() => aContact.FirstContact).Asc
                .SelectList(builder => builder.Select(() => aContact.FirstContact)
                                              .WithAlias(() => aContact.FirstContact)
                                              .Select(() => anEmployee.FirstName)
                                              .WithAlias(() => anEmployee.FirstName))
                .TransformUsing(Transformers.AliasToBean(typeof(Employee)))
                .List<Employee>();

Solution

  • For your select list, all the WithAlias methods should be using the same dto and that should also be the same class used in the transformer. Also, I don't know why you'd project into a mapped entity? Projections are for flat dto.

    That error you're seeing is due to the invalid .WithAlias(() => aContact.FirstContact)...NH transformer will now expect a FirstContact property inside the Employee class. Solution is to make a single dto containing FirstContact and FirstName properties and use that for the WithAlias and AliasToBean transformer.