Fitzchak Yitzchaki
Fitzchak Yitzchaki

Reputation: 9163

NHibernate projection: How to get a typed type using the Criteria API with projection

 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.

Upvotes: 1

Views: 1726

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

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.

Upvotes: 4

Related Questions