我正在使用 EF Core,但我并不是它的專家,尤其是在涉及以高性能方式查詢表等細節時......
所以我嘗試做的只是從帶有過濾資料的表中獲取一列的最大值。
我到目前為止是這樣的:
protected override void ReadExistingDBEntry()
{
using Model.ResultContext db = new();
// Filter Tabledata to the Rows relevant to us. the whole Table may contain 0 rows or millions of them
IQueryable<Measurement> dbMeasuringsExisting = db.Measurements
.Where(meas => meas.MeasuringInstanceGuid == Globals.MeasProgInstance.Guid
&& meas.MachineId == DBMatchingItem.Id);
if (dbMeasuringsExisting.Any())
{
// the max value we're interested in. Still dbMeasuringsExisting could contain millions of rows
iMaxMessID = dbMeasuringsExisting.Max(meas => meas.MessID);
}
}
我想要的等效 SQL 將是這樣的。
select max(MessID)
from Measurement
where MeasuringInstanceGuid = Globals.MeasProgInstance.Guid
and MachineId = DBMatchingItem.Id;
雖然上面的代碼有效(它回傳正確的值),但我認為當資料庫表變大時它會出現性能問題,因為在傳輸所有行之后在客戶端完成最大過濾,或者我在這里錯了?
如何做得更好?我希望資料庫服務器過濾我的資料。當然我不想要任何 SQL 腳本 ;-)
uj5u.com熱心網友回復:
這可以通過將 return 鍵入為 nullable 來解決,這樣您就不會收到回傳的錯誤,然后為 int 應用默認值。或者,您可以將其分配給可為空的 int。注意,這里假設 ID 的回傳型別為整數。同樣的原則也適用于 Guid。
int MaxMessID = dbMeasuringsExisting.Max(p => (int?)p.MessID) ?? 0;
不需要 Any() 陳述句,因為這會導致額外的資料庫訪問,這在這種情況下是不可取的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447857.html
