user3635120
user3635120

Reputation: 73

How to get out values from object when using Projections

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
             }

Upvotes: 0

Views: 126

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

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
}

Upvotes: 1

Related Questions