PostsController.cs 1.29 KB
Newer Older
thienvo's avatar
thienvo committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sieve.Models;
using Sieve.Services;
using SieveTests.Entities;

namespace SieveTests.Controllers
{
    [Route("api/[controller]/[action]")]
    public class PostsController : Controller
    {
        private readonly ISieveProcessor _sieveProcessor;
        private readonly ApplicationDbContext _dbContext;

        public PostsController(ISieveProcessor sieveProcessor,
            ApplicationDbContext dbContext)
        {
            _sieveProcessor = sieveProcessor;
            _dbContext = dbContext;
        }

        [HttpGet]
        public JsonResult GetAllWithSieve(SieveModel sieveModel)
        {
            var result = _dbContext.Posts.AsNoTracking();

            result = _sieveProcessor.Apply(sieveModel, result);

            return Json(result.ToList());
        }

        [HttpGet]
        public JsonResult Create(int number = 10)
        {
            for (int i = 0; i < number; i++)
            {
                _dbContext.Posts.Add(new Post());
            }

            _dbContext.SaveChanges();

            return Json(_dbContext.Posts.ToList());
        }

        [HttpGet]
        public JsonResult GetAll()
        {
            return Json(_dbContext.Posts.ToList());
        }
    }
}