【问题标题】:Entity Framework Core, execute raw SQL and parameterize table nameEntity Framework Core,执行原始 SQL 并参数化表名
【发布时间】:2020-11-27 19:33:48
【问题描述】:

我正在使用 Entity Framework Core,当我运行以下查询时,它一切都按预期工作,并从 flasher_equipment 表中选择所有实体。

public async Task<IEnumerable<BaseEquipmentType>> GetNewAvailableEquipment(string tableName)
{
    DbSet<BaseEquipmentType> dbSet = _context.Set<BaseEquipmentType>();
    IQueryable<BaseEquipmentType> types = dbSet.FromSql($"select * from flasher_equipment");
    return await types.ToArrayAsync();
}

但现在,我不想硬编码表名 (flasher_equipment),而是想将其作为参数传递。

我已尝试将代码更改如下:

public async Task<IEnumerable<BaseEquipmentType>> GetNewAvailableEquipment(string tableName)
{
    DbSet<BaseEquipmentType> dbSet = _context.Set<BaseEquipmentType>();
    IQueryable<BaseEquipmentType> types = dbSet.FromSql($"select * from {tableName}");
    return await types.ToArrayAsync();
}

我也试过了

public async Task<IEnumerable<BaseEquipmentType>> GetNewAvailableEquipment(string tableName)
{
    DbSet<BaseEquipmentType> dbSet = _context.Set<BaseEquipmentType>();
    IQueryable<BaseEquipmentType> types = dbSet.FromSql("select * from {0}", tableName);
    return await types.ToArrayAsync();
}

每次出现错误时:

Grpc.AspNetCore.Server.ServerCallHandler[6]
执行服务方法“GetByPlanIdAnImplementation”时出错。 Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-00903: 无效的表名

为什么将表名参数化为参数导致它崩溃?

【问题讨论】:

  • 但是为什么要参数化表名呢?你未来的自己正在用一条腿射击自己。

标签: c# sql entity-framework entity-framework-core


【解决方案1】:

好像是FromSqlmethod with the string interpolation的问题。

如果您在方法外部插入字符串,它可能会起作用,如:

public async Task<IEnumerable<BaseEquipmentType>> GetNewAvailableEquipment(string tableName)
{
    DbSet<BaseEquipmentType> dbSet = _context.Set<BaseEquipmentType>();
    string sqlStatement = $"select * from {tableName}"; 
    IQueryable<BaseEquipmentType> types = dbSet.FromSql(sqlStatement);
    return await types.ToArrayAsync();
}

【讨论】:

  • 这确实使它工作,但 Visual Studio 显示一个警告,说传递给 FromSQL 的表达式嵌入了不会被参数化的数据。潜在的 SQL 注入漏洞。我认为这会很好吗?
  • 我知道这一点。没事的。这只是一个警告。但是,我建议将来将其更改为新版本的 EF Core
猜你喜欢
  • 2018-02-28
  • 2019-08-27
  • 1970-01-01
  • 2016-09-26
  • 2020-10-03
  • 2017-01-10
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
相关资源
最近更新 更多