简体   繁体   English

Entity Framework Core,执行原始 SQL 并参数化表名

[英]Entity Framework Core, execute raw SQL and parameterize table name

I am using Entity Framework Core and when I run the following query it all works as expected and selects all entities from the flasher_equipment table.我正在使用 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();
}

but now, instead of hard coding the table name ( flasher_equipment ) I want to pass it as a parameter.但是现在,我不想硬编码表名( flasher_equipment ),而是想将它作为参数传递。

I've tried changing the code as follows:我尝试按如下方式更改代码:

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

and I've also tried我也试过

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

Each time I get an error:每次我得到一个错误:

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

Why is parameterizing the table name as a parameter causing it to crash?为什么将表名参数化为参数导致它崩溃?

Seems to be an problem of the FromSql method with the string interpolation .似乎是字符串插值FromSql方法的问题。

Probably it will work if you interpolate the string outside the method, as:如果您在方法外部插入字符串,它可能会起作用,如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM