0

here is what I need to do:

Receive an entity name as a string, and then return the database content of that specific table.

1- Receive entity name from the get request

        [HttpGet]
        [Route("/api/[controller]/GetByEntity")]
        public IActionResult GetAll(string entity)
        {
            try
            {
                Type type = Type.GetType(entity);
                return Ok(Unit.BasicRegisterRepository.GetByEntity<type>());
            }
            catch(Exception e)
            {
                return BadRequest(e);
            }
        }

2- Return the data

        public List<T> GetByEntity<T>() where T : class
        {
            var query = this.DbContext.Set<T>();
            var result = query.ToList();
            return result;
        }

The problem: when passing the type as parameter to the GetByEntity<type> function, I get the following error: type is a variable but used as a type

What am I doing wrong?

Thanks!

1 Answers1

-1

I found the solution! I need to use reflections to make it work.

Here is the updated code:

        [HttpGet]
        [Route("/api/[controller]/GetByEntity")]
        public IActionResult GetAll(string entity)
        {
            try
            {
                Type type = Type.GetType(entity);
                var getByEntityMethod = Unit.BasicRegisterRepository.GetType().GetMethod("GetByEntity").MakeGenericMethod(type);
                return Ok(getByEntityMethod.Invoke(Unit.BasicRegisterRepository, new Object[] { }));
            }
            catch(Exception e)
            {
                return BadRequest(e);
            }
        }