Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created April 24, 2011 15:57
Show Gist options
  • Save davybrion/939649 to your computer and use it in GitHub Desktop.
Save davybrion/939649 to your computer and use it in GitHub Desktop.
NHibernate QueryOver projection into DTO... anyone know of a cleaner way?
var orderHeaders = Session.CreateQuery(
@"select new OrderHeader(o.OrderedOn, c.Name, e.FirstName || ' ' || e.LastName)
from Order o inner join o.Customer c inner join o.Employee e")
.List<OrderHeader>();
Customer customer = null;
Employee employee = null;
var orderHeaders = Session.QueryOver<Order>()
.JoinAlias(o => o.Customer, () => customer)
.JoinAlias(o => o.Employee, () => employee)
.Select(Projections.ProjectionList()
.Add(Projections.Property<Order>(o => o.OrderedOn))
.Add(Projections.Property(() => customer.Name))
.Add(Projections.Property(() => employee.FirstName))
.Add(Projections.Property(() => employee.LastName)))
.List<Object[]>()
// the following select is the .NET Select extension method on IEnumerable, not part of the QueryOver api
.Select(values => new OrderHeader((DateTime)values[0], (string)values[1], (string)values[2] + " " + (string)values[3]));
@sdekock
Copy link

sdekock commented Apr 24, 2011

Not sure if it will work, but try this:

    Customer customer = null;
    Employee employee = null;
    OrderHeader orderHeader = null;

    var orderHeaders = Session.QueryOver<Order>()
        .JoinAlias(o => o.Customer, () => customer)
        .JoinAlias(o => o.Employee, () => employee)
        .SelectList(list => list
            .Select(o => o.OrderedOn).WithAlias(() => orderHeader.OrderedOn)
            .Select(o => customer.Name).WithAlias(() => orderHeader.Name)
            .Select(o => employee.FirstName).WithAlias(() => orderHeader.FirstName)
            .Select(o => employee.LastName).WithAlias(() => orderHeader.LastName))
        .TransformUsing(Transformers.AliasToBean<OrderHeader>())
        .Future<OrderHeader>();

If you want to keep using the constructor for OrderHeader, I guess you can use the AliasToBeanConstructor transformer.

@davybrion
Copy link
Author

i prefer to stick with the constructor so the AliasToBeanConstructor approach might work... but i was hoping to get rid of the variable declarations for the aliases and to get NHibernate to do the string concatenation like it does with the HQL example

@sdekock
Copy link

sdekock commented Apr 24, 2011

I guess you can do the string concatenation in the Select().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment