Skip to content

Instantly share code, notes, and snippets.

@mantaskaveckas
Created December 20, 2023 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mantaskaveckas/167431b449fbdfc3e90e325db7695711 to your computer and use it in GitHub Desktop.
Save mantaskaveckas/167431b449fbdfc3e90e325db7695711 to your computer and use it in GitHub Desktop.
EF CRUD sorting/filtering
// Updated Generic BaseController
[ApiController]
[Route("api/[controller]")]
public class BaseController<TEntity> : ControllerBase where TEntity : BaseEntity
{
private readonly YourDbContext _context;
public BaseController(YourDbContext context)
{
_context = context;
}
// GET: api/[controller]
[HttpGet]
public async Task<ActionResult<IEnumerable<TEntity>>> Get([FromQuery] int? sort = null, [FromQuery] string[] filters = null)
{
IQueryable<TEntity> query = _context.Set<TEntity>();
// Apply sorting
if (sort.HasValue)
{
switch ((SortOption)sort)
{
case SortOption.Option1:
query = query.OrderBy(e => e.Id);
break;
case SortOption.Option2:
query = query.OrderByDescending(e => e.Id);
break;
// Add more sorting options as needed
default:
break;
}
}
// Apply filters
if (filters != null && filters.Any())
{
foreach (var filter in filters)
{
// Apply your custom filters based on the filter parameter
// For example, if you have a property called "Name" in your entity
// query = query.Where(e => e.Name.Contains(filter));
}
}
return await query.ToListAsync();
}
// Other CRUD methods...
private bool EntityExists(int id)
{
return _context.Set<TEntity>().Any(e => e.Id == id);
}
}
// Sorting options enum
public enum SortOption
{
Option1 = 1,
Option2 = 2,
// Add more sorting options as needed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment