实体框架核心,执行原始sql并参数化表名

nwo49xxi  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(406)

我使用的是EntityFrameworkCore,当我运行下面的查询时,它会按预期工作,并从 flasher_equipment table。

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:表名无效
为什么将表名参数化为参数会导致崩溃?

uz75evzq

uz75evzq1#

似乎是个问题 FromSql 方法与字符串插值。
如果在方法外插入字符串,可能会起作用,如下所示:

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

相关问题