我正在嘗試根據早期的用戶選擇對資料庫視圖進行查詢。選擇存盤在物件串列中。
我想要實作的是將記錄添加到reportViewList如果宣告的值存在于其中一個串列中,但如果例如clientList為空,則查詢應忽略此陳述句并clients在選定的日期范圍內添加所有內容。用戶選擇存盤在物件的臨時串列中。
第一個條件是時間范圍,這很好用。我理解為什么我當前的解決方案不起作用,但我似乎無法解決如何解決它。此示例適用于同時選擇客戶和產品的情況。當串列為空時,reportViewList顯然也是空的。
我已經嘗試過添加日期范圍內的所有記錄,然后洗掉不適合的記錄,但這將是一個糟糕的解決方案并且效率不高。
非常感謝任何幫助或反饋。
List<ReportView> reportViews = new List<ReportView>();
using(var dbc = new localContext())
{
reportViewList = dbc.ReportViews.AsEnumerable()
.Where(x => x.OrderDateTime >= from && x.OrderDateTime <= to)
.Where(y => clientList.Any(x2 => x2.Id == y.ClientId)
.Where(z => productList.Any(x3 => x3.Id == z.ProductId)).ToList();
}
uj5u.com熱心網友回復:
AsEnumerable()在將所有內容添加到查詢中之前,您不應該打電話。在此處呼叫AsEnumerable()將導致您的完整資料加載到記憶體中,然后在您的應用程式中進行過濾。在沒有AsEnumerable()和之前呼叫呼叫ToList()(更好的呼叫ToListAsync())之前,您正在使用IQueryable<ReportView>. 您可以輕松地撰寫它并呼叫ToList()您的最終查詢。然后, Entity Framework 將檢查您IQueryable<ReportView>并從中生成 SQL 運算式。
對于您的問題,您只需要檢查用戶是否選擇了任何過濾器,并且僅在它們存在時才將它們添加到查詢中。
using var dbc = new localContext();
var reportViewQuery = dbc.ReportViews.AsQueryable(); // You could also write IQuryable<ReportView> reportViewQuery = dbc.ReportViews; but I prefer it this way as it is a little more save when you are refactoring.
// Assuming from and to are nullable and are null if the user has not selected them.
if (from.HasValue)
reportViewQuery = reportViewQuery.Where(r => r.OrderDateTime >= from);
if (to.HasValue)
reportViewQuery = reportViewQuery.Where(r => r.OrderDateTime <= to);
if(clientList is not null && clientList.Any())
{
var clientIds = clientList.Select(c => c.Id).ToHashSet();
reportViewQuery = reportViewQuery.Where(r => clientIds.Contains(y.ClientId));
}
if(productList is not null && productList.Any())
{
var productIds = productList.Select(p => p.Id).ToHashSet();
reportViewQuery = reportViewQuery.Where(r => productIds .Contains(r.ProductId));
}
var reportViews = await reportViewQuery.ToListAsync(); // You can also use ToList(), if you absolutely must, but I would not recommend it as it will block your current thread.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/515609.html
標籤:C#网林克
