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



我使用的是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.ServerServerCallHandler[6]执行服务方法"GetByPlanIdAnImplementation"时出错。Oracle.ManagedDataAccess.Client.OracleException(0x80004005(:ORA-00903:无效的表名

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

似乎是使用字符串插值的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();
}

最新更新