Home > database >  Linq query fails if include query has takelast limiter
Linq query fails if include query has takelast limiter

Time:01-06

I would like to use this query, so I won't get all child rows, but the last 10.

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

After the try catch turning off following error message appears:

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.

How do I have to set up my query string to get just the last child row?

CodePudding user response:

That's not how the Include method works. As implied by the example in the exception message, the expected return value of the passed predicate is a navigation property of the original object. Its use is simply to define which navigation properties should be loaded in the query results.

In your example you'd first want to define that the child navigation should be loaded:

var list = await _context.Parent
                .Include(parent => parent.Child)
                .ToListAsync();

And on a second step you'd then want to do the operation:

list.ForEach(parent => parent.Child
                       .OrderBy(gsm => gsm.Time)
                       .TakeLast(10));

More information on the Include method can be found at the microsoft documentation: https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.entityframeworkqueryableextensions.include?view=efcore-5.0

  •  Tags:  
  • Related