Sieve/SieveTests/Controllers/PostsController.cs

74 lines
2.0 KiB
C#
Raw Normal View History

2018-01-27 06:20:57 +01:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sieve.Models;
using Sieve.Services;
using SieveTests.Entities;
namespace SieveTests.Controllers
{
[Route("api/[controller]/[action]")]
2018-01-27 08:59:34 +01:00
public class PostsController : Controller
2018-01-27 06:20:57 +01:00
{
2018-02-07 05:43:09 +01:00
private ISieveProcessor _sieveProcessor;
2018-01-27 06:20:57 +01:00
private ApplicationDbContext _dbContext;
2018-02-07 05:43:09 +01:00
public PostsController(ISieveProcessor sieveProcessor,
2018-01-27 06:20:57 +01:00
ApplicationDbContext dbContext)
{
_sieveProcessor = sieveProcessor;
_dbContext = dbContext;
}
[HttpGet]
public JsonResult GetAllWithSieve(SieveModel sieveModel)
{
var result = _dbContext.Posts.AsNoTracking();
result = _sieveProcessor.ApplyAll(sieveModel, result);
return Json(result.ToList());
}
[HttpGet]
public JsonResult GetAllWithSieveAndPropertyMapping(SieveModel sieveModel)
{
var result = _dbContext.Posts.AsNoTracking();
var sieveProperties = new[]
{
SieveProperty<Post>.For(_ => _.Title, Allow.Filter, "name"),
SieveProperty<Post>.For(_ => _.CommentCount, Allow.SortAndFilter),
SieveProperty<Post>.For(_ => _.LikeCount, Allow.Sort),
SieveProperty<Post>.For(_ => _.DateCreated, Allow.SortAndFilter),
};
result = _sieveProcessor.ApplyAll(sieveModel, result, sieveProperties);
return Json(result.ToList());
}
2018-01-27 06:20:57 +01:00
[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());
}
}
}