I need an API that would expose all my DB tables as an OData API's. For this I have used scaffold db to generate all the existing models, and I have already managed to create a correct EDM model using reflection for the OData to work with. I have also created a generic controller that I can use as a base controller for each of my models. And it looks like this:
public class GenericController<TEntity> : ODataController
where TEntity : class, new()
{
private readonly DbContext _context;
public GenericController(DbContext context)
{
_context = context;
}
[HttpGet]
[EnableQuery(PageSize = 1000)]
[Route("odata/{Controller}")]
public async Task<ActionResult<IEnumerable<TEntity>>> GetObjects()
{
try
{
if (_context.Set<TEntity>() == null)
{
return NotFound();
}
var obj = await _context.Set<TEntity>().ToListAsync();
return Ok(obj);
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
I can use this controller as a base for each of my models by manually creating a controller per model like this:
[ApiController]
public class ModelController : GenericController<MyModel>
{
public ActiviteitenObjectsController(Dbcontext context) : base(context)
{
}
}
And it works fine with OData filters and everything. But the problem is I have way too many tables to be able to manually create the controllers for every single one of them.
I know you can use app.MapGet("/", () => "Hello World!") to map the endpoints to a delegate or even use HTTPContext inside of it, but I can't figure out how to use it in my case, so that it would work with OData as well. Are there any approaches I can use to solve my problem?