I have put together a GET
request that returns the last n
(5) records on WebApi. Simply creating a call to get the entire list back async, then count the last five items, add them to a List of the custom type, that is Application
in this case, then add then to a new list and return that.
Is there a more efficient way to run this query using Entity Framework core on .Net Core 6 webapi?
Here is my current code:
// GET: api/Application/last5
[HttpGet("last5")]
public async Task<ActionResult<IEnumerable<Application>>> Get5Applications()
{
var list = await _context.Applications.ToListAsync();
List<Application> returnedData = new List<Application>();
for (int i = Math.Max(0, list.Count - 5); i < list.Count; i)
{
returnedData.Add(list[i]);
}
return returnedData;
}
CodePudding user response:
Try
_context.Applications.OrderByDescending(x => x.sortingproperty).Take(5);
System.Linq provides a Take function but it looks like you need to sort by decending order. You need to have some sort of property you're wanting to sort by. Replace sortingproperty with anything that fits your needs, normally an ID of some sort. I hope this helps. If you don't need the reversed order then you can use _context.Applications.Take(5)
CodePudding user response:
If you want to get Last insert items. You can try 2 ways. I mentioned both of them followed photos. In this example I have product entity and I saved some items in database, then tried both worked correctly. Also you can order by any column if you want. I ordered by id because it is auto increment