2017-08-25 79 views
0

我有以下方法調用我的數據庫中的proc並將結果返回給數據集。然後使用該數據集來填充我使用MVC & cshtml呈現的表格。來自proc調用的分頁SQL結果

的方法是:

public DataSet CallProcToDataSet(string procName) 
{ 
    DataSet ds = new DataSet(); 

    string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString; 

    using (SqlConnection con = new SqlConnection(constr)) 
    { 

     using (SqlCommand cmd = new SqlCommand(procName)) 
     { 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Connection = con; 


      using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) 
      { 
       sda.Fill(ds); 
      } 
     } 
    } 

    return ds; 
} 

這工作得很好,但我想要的是具有分頁這樣只有10同時顯示結果的一些方法。對於我來說,實現這一目標的最佳方式是不涉及對proc調用的任何更改?

+0

您目前使用什麼分頁方法?這篇文章可以幫助你決定:https://stackoverflow.com/questions/446196/how-do-i-do-pagination-in-asp-net-mvc。 –

+0

@TetsuyaYamamoto我目前沒有使用任何東西。但我會看看鏈接 – N0xus

回答

0

可以使用Fill方法的此重載

public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables); 

(鏈接:https://msdn.microsoft.com/en-us/library/0z5wy74x(v=vs.110).aspx) 這樣,您將只返回的記錄的子集,而無需修改您的存儲過程。

例(MSTest的)

[TestMethod] 
     public void TestMethod1() 
     { 
      DataSet ds = new DataSet(); 
      var procName = "sp_server_info"; 
      string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString; 
      var tblName = "result"; 
      var tbls = new[] { ds.Tables.Add(tblName) }; 
      using (SqlConnection con = new SqlConnection(constr)) 
      { 
       using (SqlCommand cmd = new SqlCommand(procName)) 
       { 
        cmd.CommandType = CommandType.StoredProcedure; 
        cmd.Connection = con; 

        using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) 
        { 
         sda.Fill(0, 10, tbls); 
        } 
       } 
      } 
      Assert.AreEqual(tbls[0].Rows.Count, 10); 

     } 
+0

謝謝。那麼呈現頁面選項的最佳方式是什麼?就像我有100個記錄一樣,我應該有10個頁面可以進行閱讀。你會建議什麼? – N0xus

+0

不客氣,我會問一個單獨的問題,指定你已經在數據層級進行分頁。 –

0

嘗試以下操作:

  DataSet ds = new DataSet(); 
      DataTable dt = ds.Tables[0]; 

      for (int i = 0; i < dt.Rows.Count; i += 10) 
      { 
       DataTable pageTable = dt.AsEnumerable().Where((x, n) => (n >= i) && (n < i + 10)).CopyToDataTable(); 
      } 
+0

'skip'和'take'會更容易嗎? – Stefan

+0

OP尚未決定使用哪種分頁方法。所以有可能使用其他方法,如Skip&Take。 –

+0

我剛想到Where()方法。 – jdweng