如何将泛型类型传递给泛型方法

时间:2020-10-23 19:37:45

标签: c# entity-framework

这是我需要做的:

以字符串形式接收实体名称,然后返回该特定表的数据库内容。

1-从获取请求中接收实体名称

        [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-返回数据

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

问题:将type作为参数传递给GetByEntity<type>函数时,出现以下错误: type is a variable but used as a type

我在做什么错了?

谢谢!

1 个答案:

答案 0 :(得分:-1)

我找到了解决方案!我需要使用反射使其起作用。

这是更新的代码:

        [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);
            }
        }