This overload of the method 'System.Linq.Queryable.TakeLast' is currently not supported

asp.net-core entity-framework-core linq

Question

I have an ASP .Net Core 2.2 Web API using Entity Framework Core. It connects to a MySQL database using the latest version of Pomelo. When I try to execute the Linq function "TakeLast", like this:

var messages = dbContext.Messages
                   .TakeLast(5)
                   .ToList();

I get this error:

Exception thrown: 'System.NotSupportedException' in Remotion.Linq.dll

System.NotSupportedException: Could not parse expression 'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[PropWorx.API.Models.Message]).TakeLast(__p_0)': This overload of the method 'System.Linq.Queryable.TakeLast' is currently not supported.

The Ling function "Take" works - but "TakeLast" doesn't. Is this a limitation of MySql? Or Pomelo? Any workaround?

Thanks

1
1
6/28/2019 2:23:59 PM

Accepted Answer

Each provider is responsible for implementing the LINQ expression translation that works for their particular platform. It would appear, yes, that Pomelo has not provided support for TakeLast.

As far as workarounds go, two things. First you should never use Skip/Take without an order by clause. The default order is going to be primary key, but depending on the type of the key, that could end up almost being entirely random. It's always better to be explicit about the ordering, so you understand exactly what's being taken from the results.

Second, assuming you have an ordering, to get TakeLast functionality, you simply need to reverse the ordering and use Take instead. For example, lets assume you're pulling messages by creation date:

var messages = dbContext.Messages.OrderBy(o => o.Created).TakeLast(5).ToList();

What you're really saying here is that you want the ones with the latest created date, so you could do instead:

var messages = dbContext.Messages.OrderByDescending(o => o.Created).Take(5).ToList();

To achieve the same result.

2
6/28/2019 2:31:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow