我想使用這個查詢,所以我不會得到所有子行,而是最后 10 個。
var list = await _context.Parent
.Include(gs => gs.Child
.OrderBy(gsm => gsm.Time)
.TakeLast(10))
.ToListAsync();
try catch 關閉后出現以下錯誤訊息:
System.InvalidOperationException:運算式“gs.GreenSpeedMess.AsQueryable().OrderByDescending(gsm => gsm.MesTime).TakeLast(10)”在“包含”操作中無效,因為它不代表屬性訪問:“t => t.MyProperty'。要定位在派生型別上宣告的導航,請使用強制轉換 ('t => ((Derived)t).MyProperty') 或 'as' 運算子 ('t => (t as Derived).MyProperty')。集合導航訪問可以通過組合 Where、OrderBy(Descending)、ThenBy(Descending)、Skip 或 Take 操作進行過濾。有關包含相關資料的詳細資訊,請參閱 http://go.microsoft.com/fwlink/?LinkID=746393。
如何設定查詢字串以獲取最后一個子行?
uj5u.com熱心網友回復:
這不是Include方法的作業原理。正如例外訊息中的示例所暗示的,傳遞的謂詞的預期回傳值是原始物件的導航屬性。它的用途只是定義應在查詢結果中加載哪些導航屬性。
在您的示例中,您首先要定義應加載子導航:
var list = await _context.Parent
.Include(parent => parent.Child)
.ToListAsync();
然后在第二步中,您需要執行以下操作:
list.ForEach(parent => parent.Child
.OrderBy(gsm => gsm.Time)
.TakeLast(10));
有關該Include方法的更多資訊,請參見 microsoft 檔案:https : //docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.entityframeworkqueryableextensions.include? view = efcore- 5.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/405938.html
標籤:
