2016-05-04 86 views
0

我一直在尋找代碼,如果我可以分頁EF中的大數據,例如從1到100 ...或更多,Web應用程序真的很慢。 我在這裏有代碼,但我還找不到解決方案。實體框架分頁

我真的需要使頁面中的數據或使數據視圖更快 記錄超過(1,5000,000)記錄。 請大家如果有人有EF分頁的任何代碼或解決方案或數據可以更快地回覆我。

謝謝你們,

[代碼]

var openComplaintsAssignedToOffice = individual.Office.AssignedComplaints 
                 .ToArray() 
                 .Where(n => n.Individuals.Any(e => e.Employed)) 
                 .ToArray() ; 

if (!complaintModel.ShowClosedComplaints) 
{ 
    openComplaintsAssignedToOffice = openComplaintsAssignedToOffice.Where(c => c.CurrentStatus != ComplaintStatus.Closed) 
                    .ToArray(); 
} 

complaintModel.OpenComplaintsAssignedToMyOffice = openComplaintsAssignedToOffice.OrderByDescending(c => c.UpdatedDateTime) 
                       .ToArray(); 
complaintModel.OpenComplaintsAssignedToMyOffice = openComplaintsAssignedToOffice.OrderByDescending(c => c.UpdatedDateTime) 
                       .ToArray(); 
return complaintModel; 
+0

你只是尋找'.Skip()'和'。取()'功能? – David

+0

你正在提出一個非常微不足道的問題,並附帶代碼,這些代碼似乎並不相關。或者,更確切地說,代碼似乎會導致問題本身。 –

+0

http://sqlperformance.com/2015/01/t-sql-queries/pagination-with-offset-fetch – ErikEJ

回答

1

你沒有具體指明你正在尋找網頁數據,所以爲了簡單起見,我將承擔起它在這裏:

individual.Office.AssignedComplaints 

(雖然,作爲一個側面說明,你似乎是關於一個.ToArray()扔在這裏和那裏很傲慢,要知道這可能極大地迫使系統衝擊性能許多記錄加載到內存上可能有更好了數據源本身上執行這些記錄進行過濾器前。)

您可以使用.Skip().Take()功能有效頁面結果。例如,假設你有這些值:

var pageSize = 10; 
var currentPage = 3; // 0-indexed, of course 

鑑於這些,你希望看到的記錄30-39,是否正確?所以,你會使用這些值來頁的數據:

individual.Office.AssignedComplaints.Skip(pageSize * currentPage).Take(pageSize) 

這將導致跳過第30條記錄(0-29),並考慮在未來10個記錄,忽略其它。有效返回總結果集的「第3頁」。

此分頁可應用於整體表達式樹中可以過濾結果集的任何位置。在排序之前或之後,在.Where()子句之前或之後,等等。根據您打算如何塑造和呈現數據,它在邏輯上屬於您。

+0

謝謝大衛,你的代碼運行良好。 –

1

通常,您將使用Skip()Take()方法來處理分頁數據。 Skip()將確定要「跳過」多少個元素來定義頁面的起始點,並確定要抓取多少個元素。

// This will skip the first 10 records and take the next 20 
var page = data.Skip(10).Take(20); 

考慮Deferred Execution

一個非常重要的事情時要考慮處理這是您要儘可能長的時間推遲執行。諸如ToList()ToArray()等方法實際上會將您的值存儲在內存中,這是您想要避免的,特別是對於大型數據集。

如果您可以避免調用這些方法,您將確保查詢本身只執行一次(因此只返回一頁記錄,而不是整個數據集,然後在內存中分頁)。

,如下圖所示,您可能會重構代碼中使用分頁:

// Define your page size and initial page 
var page = 0; 
var pageSize = 20; 
// Get any open complaints 
var openComplaints = individual.Office.AssignedComplaints.Where(n => n.Individuals.Any(e => e.Employed)); 
// Determine if complaints should be shown 
if (!complaintModel.ShowClosedComplaints) 
{ 
    openComplaints = openComplaints.Where(c => c.CurrentStatus != ComplaintStatus.Closed);                
} 
// Finally order and page your data 
return openComplaints.OrderByDescending(c => c.UpdatedDateTime) 
        .Skip(page * pageSize) 
        .Take(pageSize) 
        .ToArray(); 
+0

我想感謝你的代碼Rion,它實際上是工作,如果我改變了這樣的 individual.Office.AssignedComplaints.Skip(pageSize * currentPage).Take(pageSize) –