使用投影时如何从对象中获取值

时间:2014-06-18 08:04:32

标签: c# nhibernate

使用投影时如何从对象中取出值。 有什么建议? 这是代码的示例

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
             }

1 个答案:

答案 0 :(得分:1)

我们在这里需要的是使用DTO对象

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; }
}

现在我们将使用DTO创建别名

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
}