![](/img/trans.png)
[英]'Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.'
[英]Linq Count() timing out -Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding
我有一個 linq 查詢,它試圖從數據庫中獲取大約 500K 條記錄。 我有一個 Count() 最終超時。
我想知道我的 linq 查詢是否包含 5000 條或更多條記錄。 我不計算所有記錄,只需要檢查 linq 是否包含 5000 條記錄。
有沒有什么有效的方法可以在不調用 Count() 的情況下檢查 linq 中是否有 5000 條或更多條記錄? 我正在使用 EF 核心 3.1。
林克查詢:
var results = (from a in RepoContext.Employee
join b in RepoContext.Program on a.ProgramId equals b.ProgramId
where a.ActiveFlag == true
&& b.ClientId == 2
select new RAManufacturerDto
{
BusinessName = a.BusinessName,
ClientId = a.ClientId.Value,
ClientName = b.ClientName
DCode = b.DCode,
StoreId = b.StoreId,
ProgramId = a.ProgramId
});
bool isRecordsLimitReached = results.Count() > 5000;
嘗試對結果執行 Count() 時出現錯誤。 我只想知道它是否包含超過 5000 條記錄。
直接使用 linq,假設您正確配置了 dbcontext 並且在 onmodelcreating 中定義了兩者之間的這種關系,請將代碼移動到 RepoContext 中。 (如果對定義關系有疑問,請查看: https : //docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key )
DbSet<Employee> Employees {get;set;}
DbSet<Program> Programs {get;set;}
public bool HasMoreThan(int number) {
var count = RepoContext.Employee.Include(x => x.Program).Count(y =>
y.ActiveFlag == true && y.Program.ClientId == 2);
return count >= number;
}
試着跳過 5000 條記錄,如果有記錄 - 我們已經達到了我們的目標:
bool isRecordsLimitReached = results.Skip(5000).Any();
如果您只需要獲取計數,則無需選擇所有這些屬性。 您可以通過僅選擇不可為空的屬性之一來優化此查詢。
var results = (from a in RepoContext.Employee
join b in RepoContext.Program on a.ProgramId equals b.ProgramId
where a.ActiveFlag == true &&
b.ClientId == 2
select a.Id); //Id = Primary Key of the Employee database
bool isRecordsLimitReached = results.Count() > 5000;
如果您仍然遇到超時,那么您可能需要在 Program 表上的外鍵中添加一個索引(如果它尚未存在)。 ActiveFlag 和 ClientId 的額外索引也不會受到影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.