如果包含查询具有 takelast 限制器,则 Linq 查询失败

Linq query fails if include query has takelast limiter

我想使用这个查询,所以我不会得到所有子行,而是最后 10 个。

var list = await _context.Parent
                .Include(gs => gs.Child
                                    .OrderBy(gsm => gsm.Time)
                                    .TakeLast(10))
                .ToListAsync();

try catch 关闭后出现以下错误消息:

System.InvalidOperationException: The expression 'gs.GreenSpeedMess.AsQueryable().OrderByDescending(gsm => gsm.MesTime).TakeLast(10)' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

我必须如何设置我的查询字符串才能只获取最后一个子行?

这不是 Include 方法的工作原理。正如异常消息中的示例所暗示的,传递的谓词的预期 return 值是原始对象的导航 属性。 它的用途只是定义应该在查询结果中加载哪些导航属性。

在您的示例中,您首先要定义应加载子导航:

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