【问题标题】:when try to get columns exist on table passed to function I get error当尝试获取传递给函数的表上存在的列时出现错误
【发布时间】:2019-03-12 01:58:16
【问题描述】:

问题

当尝试获取传递给函数的表上存在的列时,我得到错误

数据库外观不包含 SqlQuery 的定义,也没有可访问的扩展 方法 SqlQuery

我首先在 asp.net core 2.1 web api 代码上工作

我尝试设计函数在这里给出表名,它会返回列存在于这个

表格但我得到编译错误

数据库外观不包含 SqlQuery 的定义并且没有可访问的扩展 方法 SqlQuery

那么如何解决这个错误

public class TabDbContext : DbContext
    {
        public TabDbContext(DbContextOptions<TabDbContext> options)
: base(options)
        { }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Employee> Departments { get; set; }

ON 控制器 API 我这样做:

public class EmployeesController : ControllerBase
    {
        private readonly TabDbContext _context;

        public EmployeesController(TabDbContext context)
        {
            _context = context;
        }
 public List<string> GetColumnNames(string tablename)
        {

                var sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = @TableName";
                SqlParameter sqlParameter = new SqlParameter("TableName", tablename);
                var query = _context.Database.SqlQuery<string>(sql, sqlParameter).ToList();
                return query;

        }

预期结果

Employees 表有两列 EmployeeId,EmployeeName

调用函数为 GetColumnNames(Employees)

会回来

员工编号

员工姓名

【问题讨论】:

    标签: asp.net-core-webapi asp.net-core-2.1 ado.net-entity-data-model entity-framework-core-2.1


    【解决方案1】:

    您可以使用 FromSql 扩展方法开始基于 EF Core 2.1 中的原始 SQL 查询的 LINQ 查询:

    https://docs.microsoft.com/en-us/ef/core/querying/raw-sql

    然后您的代码将修改为:

    var sqlParameter = new SqlParameter("TableName", tablename);
    var employees= _context.Employees
                   .FromSql("select COLUMN_NAME from information_schema.COLUMNS where table_name = @TableName", sqlParameter )
                   .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 2011-06-02
      • 1970-01-01
      • 2018-04-08
      • 2020-09-28
      • 2017-01-11
      相关资源
      最近更新 更多