Question

 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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top