开发者

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

开发者 https://www.devze.com 2022-12-19 22:55 出处:网络
List<object[]> products = GetSession().CreateCriteria<Product>() .SetProjection(Projections.ProjectionList()
 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&开发者_JAVA技巧gt; type?

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号