2017-07-30 95 views
0

擁有IQueryOver,我如何從它獲取行計數,而無需從DB加載所有行? QueryOver有RowCount()方法,但如果基礎查詢有不同,它會丟棄它們。從IQueryOver獲取計數,無需從DB加載行

*****更新*****

SQL genearted爲QueryOver.RowCount(正如你看到它丟棄DISTINCT):

exec sp_executesql N' 
SELECT count(*) as y0_ 
FROM dbo.OPR_STL_DCM this_ 
left outer join dbo.OPR_STL_LN_ITM lineitem1_ 
on 
this_.DCM_ID=lineitem1_.DCM_ID 
left outer join dbo.OPR_STL_DY_LN_ITM daylineite2_ 
on 
lineitem1_.DCM_ID=daylineite2_.DCM_ID and 
lineitem1_.TND_ID=daylineite2_.TND_ID 
WHERE 
daylineite2_.BSNS_DT >= @p0 and 
daylineite2_.BSNS_DT <= @p1' 
,N'@p0 datetime,@p1 datetime',@p0='2016-07-22 00:00:00',@p1='2016-08-21 23:59:59' 

生成的SQL QueryOver

exec sp_executesql N' 
SELECT distinct this_.DCM_ID as y0_, 
    this_.RTL_STR_ID as y1_, 
    this_.WS_ID as y2_, 
    this_.BSNS_DT as y3_, 
    this_.OPR_ID as y4_, 
    this_.TND_RPSTY_ID as y5_, 
    this_.IS_CNC as y6_, 
    this_.IS_SNG_DY_STL as y7_, 
    this_.BGN_DT_TM as y8_, 
    this_.END_DT_TM as y9_ 
FROM dbo.OPR_STL_DCM this_ 
left outer join dbo.OPR_STL_LN_ITM lineitem1_ 
on 
this_.DCM_ID=lineitem1_.DCM_ID 
left outer join dbo.OPR_STL_DY_LN_ITM daylineite2_ 
on 
lineitem1_.DCM_ID=daylineite2_.DCM_ID and 
lineitem1_.TND_ID=daylineite2_.TND_ID 
WHERE daylineite2_.BSNS_DT >= @p1 and 
daylineite2_.BSNS_DT <= @p2' 
,N'@p1 datetime,@p2 datetime',@p0=20,@p1='2016-07-22 00:00:00',@p2='2016-08-21 23:59:59' 
+0

正如你看到的,行數方法沒有得到查詢結果的實際計數! –

回答

0

最後,我找到了解決辦法。 注入MyMsSql2008Dialect爲nhibernate.dialect值。 該類將行數插入名爲#TempCount的臨時表中;現在你可以從#TempCount中讀取行數。請注意,這必須在會話中完成。

public class MyMsSql2008Dialect : MsSql2008Dialect 
{ 
    public override SqlString GetLimitString(SqlString queryString, SqlString offset, SqlString limit) 
    { 
     SqlString limitString = base.GetLimitString(queryString, offset, limit); 

     SqlStringBuilder ssb = new SqlStringBuilder(); 

     string resultCountQuery = string.Format(
      @" 
       INSERT INTO #TempCount 
       SElECT COUNT(*) AS Count FROM 
       (
        {0} 
       ) AS _queryResult 
      " 
      , queryString); 

     ssb.Add(resultCountQuery); 

     SqlStringBuilder newLimitString = new SqlStringBuilder(); 
     newLimitString.Add(limitString).Add(Environment.NewLine).Add(ssb.ToSqlString()); 

     return newLimitString.ToSqlString(); 
    } 
} 

而獲得的行數:

int rowsCount = session.CreateSQLQuery("SELECT TOP 1 * FROM #TempCount").UniqueResult<int>(); 
0

我認爲這不支持IQueryOver,但不要在此引用我。

我得到了它的ICriteria雖然工作..

crit.SetProjection(Projections.Count(Projections.Distinct(Projections.Id())));