skip to Main Content

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;
}

2

Answers


  1. 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)

    Login or Signup to reply.
  2. 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

    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly AppDbContext _context;
    
        public ProductController(AppDbContext context)
        {
            _context = context;
        }
    
        [HttpGet("GetLastItems1/{take}")]
        public IEnumerable<Product> GetLastItems1(int take) => _context.Products
                                                                        .TakeLast(take)
                                                                        .ToList();
    
        [HttpGet("GetLastItems2/{take}")]
        public IEnumerable<Product> GetLastItems2(int take) => _context.Products
                                                                        .OrderByDescending(x => x.Id)
                                                                        .Take(take)
                                                                        .OrderBy(x => x.Id)
                                                                        .ToList();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search