0

How to get out values from object when using Projections. Any suggestions? This is an example of code

var productsGrouped = session.QueryOver<Product>()
.Select(Projections.Group<Product>(p => p.Category),
Projections.Avg<Product>(p => p.UnitPrice),
Projections.Sum<Product>(p => p.UnitsOnStock),
Projections.RowCount())
.List<object[]>(); 

foreach (var product in productsGrouped)
             {
                 Console.WriteLine(product.Category);  //Dont Work
             }
rene
  • 41,474
  • 78
  • 114
  • 152
user3635120
  • 73
  • 3
  • 10

1 Answers1

1

What we do need here, is to use DTO Object

public class ProductDTO
{
    public virtual string Category { get ; set; }
    public virtual decimal UnitPrice { get; set; }
    public virtual decimal UnitsOnStock { get; set; }
    public virtual int RowCount { get; set; }
}

And now we will use the DTO to create alias

ProductDTO dto = null;

var productsGrouped = session.QueryOver<Product>()
    // let's fill projection list with all the SUM, COUNT but als WITH ALIAS
    .Select(Projections.ProjectionList()
        .Add(Projections.Group<Product>(p => p.Category)
            .WithAlias(() => dto.Category))
        .Add(Projections.Avg<Product>(p => p.UnitPrice)
            .WithAlias(() => dto.UnitPrice))
        .Add(Projections.Sum<Product>(p => p.UnitsOnStock)
            .WithAlias(() => dto.UnitsOnStock))
        .Add(Projections.RowCount()
            .WithAlias(() => dto.RowCount))
    )
    // here we instruct NHibernate to convert projection into our object DTO
    .TransformUsing(Transformers.AliasToBean<ProductDTO>())
    // fully typed result
    .List<ProductDTO>();

// now it is fully qualified object
foreach (var product in productsGrouped)
{
    Console.WriteLine(product.Category);  //Dont Work
}
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335