从唯一ID获取行数

时间:2016-07-14 13:17:21

标签: nhibernate fluent-nhibernate nhibernate-criteria rowcount

我们假设我有这个简单的n-n表格(在peopleproduct之间):

//id    people_id    product_id
  1         1            1  
  2         1            3  
  3         1            5
  4         2            1

这个类(已映射):

public class PeopleProduct
{
    public virtual int TableId { get; set; } //Mapped to id
    public virtual int PeopleId { get; set; } //Mapped to people_id
    public virtual Product Product { get; set; } //Mapped to product_id
}

正如您所看到的,有两个people,第一个有3个products,第二个只有1个。

如何使用CreateCriteria获取唯一people_id的计数?

我目前正在尝试使用这个:

var crit = StatelessSession.CreateCriteria<PeopleProduct>()
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Count<PeopleProduct>(c => c.PeopleId))
        .Add(Projections.Group<PeopleProduct>(g => g.PeopleId)));

var count = Convert.ToInt64(crit.UniqueResult());

但它总是返回一个包含[count,id]数组的列表:

[3, 1] and [2, 1]

这不是最佳结果,因为此表可能会返回数千个people_id

2 个答案:

答案 0 :(得分:1)

使用CountDistinct

var numberOfDistinctPeople = StatelessSession.CreateCriteria<PeopleProduct>()
    .SetProjection(Projections.CountDistinct<PeopleProduct>(c => c.PeopleId))
    .UniqueResult();

顺便说一句,您是否知道可以使用QueryOver,这与更好的语法相同? HQL / Linq更强大,更适合用于像这样的静态查询。

答案 1 :(得分:0)

最后,这有效!

var crit = StatelessSession.CreateCriteria<PeopleProduct>()
    .SetProjection(Projections.ProjectionList()
            .Add(Projections.Count(Projections.Distinct(
                    Projections.Property<PeopleProduct>(p => p.PeopleId)))));

var count = Convert.ToInt64(crit.UniqueResult());

编辑:有一个更好的答案(而且更简洁)...