首页 > 解决方案 > 如何将泛型类型传递给泛型方法

问题描述

这是我需要做的:

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

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

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

我究竟做错了什么?

谢谢!

标签: c#entity-framework

解决方案


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

这是更新的代码:

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

推荐阅读