【问题标题】:Sql Parameterising with PgSql using EF Core and C#使用 EF Core 和 C# 使用 PgSql 进行 Sql 参数化
【发布时间】:2021-03-04 15:18:12
【问题描述】:

我正在尝试使用带有参数的 C# 和 EF Core 执行 SQL 查询。我相信参数被忽略了

我使用的代码是

string sqlQuery = @"SELECT ""Studies"".* 
                    FROM ""Studies"" 
                    INNER JOIN ""Searches"" on ""Searches"".""StudyId"" =""Studies"".""StudyId"" 
                    WHERE ""Searches"".""Document"" @@ to_tsquery('@text')";

      
IQueryable<Study> studies = _studiesContext.Studies.FromSqlRaw(sqlQuery, new NpgsqlParameter("@text", "fire"));

我期望发生的是,我从数据库中返回相同的行,就好像我在 Postgres 控制台中运行以下命令一样:

SELECT "Studies"."StudyId", 
        "Studies"."Title",
        "Studies"."Author"
FROM "Studies"
INNER JOIN "Searches" on "Searches"."StudyId" ="Studies"."StudyId" 
WHERE "Searches"."Document" @@ to_tsquery('fire');

但我没有。相反,我得到的结果与在 Postgres 控制台中键入以下内容相同:

SELECT "Studies"."StudyId", 
        "Studies"."Title",
        "Studies"."Author"
FROM "Studies"
INNER JOIN "Searches" on "Searches"."StudyId" ="Studies"."StudyId" 
WHERE "Searches"."Document" @@ to_tsquery('@text');

我相信在我的查询中@text 不会被fire 替换

EF Core 日志显示:

Executed DbCommand (10ms) [Parameters=[@text='?'], CommandType='Text', CommandTimeout='30']
SELECT "Studies".*
FROM "Studies"
INNER JOIN "Searches" on "Searches"."StudyId" ="Studies"."StudyId"
WHERE "Searches"."Document" @@ to_tsquery('@text')

我觉得我遗漏了一些应该很明显的东西?

【问题讨论】:

  • 去掉单引号:to_tsquery(@text).

标签: c# .net entity-framework-core npgsql


【解决方案1】:

我认为@text 周围的单引号是问题所在,请尝试不使用它们

【讨论】:

    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2018-07-19
    • 2021-12-29
    相关资源
    最近更新 更多