views:

520

answers:

3
 List<object[]> products = GetSession().CreateCriteria<Product>()
            .SetProjection(Projections.ProjectionList()
                               .Add(Projections.Property("Id"))
                               .Add(Projections.Property("Name"))
                               .Add(Projections.Property("Price"))
             )
             .List();
public class ProductRow
{
     public int Id { get; set; }
     public string Name { get; set; }
     public double Price { get; set; }
}

How can I get the result as a List<ProductRow> type?

I see there is a function Projection.Cast, but I don't see any documentation on how to use it.

+2  A: 

You may try setting a result transformer:

var result = GetSession()
    .CreateCriteria<Product>()
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property("Id"), "Id")
        .Add(Projections.Property("Name"), "Name")
        .Add(Projections.Property("Price"), "Price")
    )
    .SetResultTransformer(Transformers.AliasToBean<ProductRow>())
    .List<ProductRow>();

Note the usage of alias pointing to a property name of a ProductRow when adding each projection.

Darin Dimitrov
`.Add(Projections.Property("Category.Name"), "Category")` in this case I getting error: 'could not resolve property: Category.Name of Project.Domain.Model.Product'.
Mendy
I believe you need to add an alias for your Category property and use the alias name instead. So if you'd use AddAlias to give "Category" an alias of "c", you'd use "c.Name" instead of "Category.Name".
Kristoffer
A: 

.Add(Projections.Property("Category.Name"), "Category") in this case I getting error: 'could not resolve property: Category.Name of Project.Domain.Model.Product'.

anyone has solved this problem?

reggieboyYEAH
A: 

I haven't been able to find a solution to this problem specifically. I posted a similiar question a few days ago. (http://stackoverflow.com/questions/3921457/nhibernate-entity-access-through-projection) The error message is becuase NHibernate is looking for a property named Category in your Product class. I assume there is not one. The ony work around I have been able to find so far is using a DTO. As well, looking deeper into dynamic DTO generators and Dynamic LINQ to NHibernate using Expression Trees, Lambda Expressions and-or an ExpressionSelector. All of which seem relatively complicated. I wish there was a simple solution for setting entities dynamiclly, I.e. projection.

Ben