How do I select the Count(*) of an nHibernate Subq

2019-02-13 05:23发布

I need to do the following for the purposes of paging a query in nHibernate:

Select count(*) from 
(Select e.ID,e.Name from Object as e where...)

I have tried the following,

select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...)

and I get an nHibernate Exception saying I cannot convert Object to int32.

Any ideas on the required syntax?

EDIT

The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with Count(*) because Count(*) distinct is not a valid syntax, and distinct count(*) is meaningless.

6条回答
戒情不戒烟
2楼-- · 2019-02-13 05:53

Do you need e.Id,e.Name?

just do

select count(*) from Object where.....

查看更多
仙女界的扛把子
3楼-- · 2019-02-13 05:55

Solved My own question by modifying Geir-Tore's answer.....

 IList results = session.CreateMultiQuery()
        .Add(session.CreateQuery("from Orders o").SetFirstResult(pageindex).SetMaxResults(pagesize))
        .Add(session.CreateQuery("select count(distinct e.Id) from Orders o where..."))
        .List();
    return results;
查看更多
做个烂人
4楼-- · 2019-02-13 06:03

Here is a draft of how I do it:

Query:

public IList GetOrders(int pageindex, int pagesize)
{
    IList results = session.CreateMultiQuery()
        .Add(session.CreateQuery("from Orders o").SetFirstResult(pageindex).SetMaxResults(pagesize))
        .Add(session.CreateQuery("select count(*) from Orders o"))
        .List();
    return results;
}

ObjectDataSource:

[DataObjectMethod(DataObjectMethodType.Select)]
public DataTable GetOrders(int startRowIndex, int maximumRows)
{
    IList result = dao.GetOrders(startRowIndex, maximumRows);
    _count = Convert.ToInt32(((IList)result[1])[0]);

    return DataTableFromIList((IList)result[0]); //Basically creates a DataTable from the IList of Orders
}
查看更多
我只想做你的唯一
5楼-- · 2019-02-13 06:08

I prefer,

    public IList GetOrders(int pageindex, int pagesize, out int total)
    {
            var results = session.CreateQuery().Add(session.CreateQuery("from Orders o").SetFirstResult(pageindex).SetMaxResults(pagesize));

            var wCriteriaCount = (ICriteria)results.Clone());

            wCriteriaCount.SetProjection(Projections.RowCount());

            total = Convert.ToInt32(wCriteriaCount.UniqueResult());


            return results.List();
    }
查看更多
Animai°情兽
6楼-- · 2019-02-13 06:16
var session = GetSession();
var criteria = session.CreateCriteria(typeof(Order))
                    .Add(Restrictions.Eq("Product", product))
                    .SetProjection(Projections.CountDistinct("Price"));
return (int) criteria.UniqueResult();
查看更多
仙女界的扛把子
7楼-- · 2019-02-13 06:19

NHibernate 3.0 allows Linq query.

Try this

int count = session.QueryOver<Orders>().RowCount();
查看更多
登录 后发表回答