【问题标题】:Dapper.net "where ... in" query doesn't work with PostgreSQLDapper.net “where ... in”查询不适用于 PostgreSQL
【发布时间】:2016-11-06 09:54:14
【问题描述】:

以下查询总是产生错误 "42601: syntax error at or near "$1" ”。

connection.Query<CarStatsProjection>(
                @"select manufacturer, model, year, AVG(price) as averageprice, AVG(miles) as averagemiles, COUNT(*) as count
                        from products
                        where manufacturer IN @manufacturers 
                            AND model IN @models
                            AND year IN @years
                        group by manufacturer, model, year",
                new { manufacturers = new[] { "BMW", "AUDI" }, 
                      models = new[] { "M4", "A3" }, 
                      years = new[] { 2016, 2015 } });

我已经通过在下面创建一个方法并调用它来内联来构建 SQL 查询来解决这个问题。想知道 Dapper 是否可以使用对象参数处理这个问题?

 public static string ToInSql(this IEnumerable<object> values)
    {
        var flattened = values.Select(x => $"'{x}'");
        var flatString = string.Join(", ", flattened);

        return $"({flatString})";
    }

【问题讨论】:

  • 您确定这是导致错误的代码吗? SQL 字符串有两个参数(制造商和型号),但是有三个参数被传递给 Dapper(制造商、型号和年份);但是,Dapper 会忽略未使用的参数,所以这不是问题。 IN 子句和 Dapper 约定的使用也是正确的。 SQL 字符串以字符串插值符号开头,但没有发生字符串插值。您的代码中似乎还缺少其他内容;也许是字符串插值?
  • 您好 - 这是因为我已经开始使用下面的 ToInSql() 方法并且只是撤消了一些事情。正如您在更新的帖子中看到的那样,我已正确还原它。谢谢

标签: c# .net postgresql dapper


【解决方案1】:

PostgreSQL IN 运算符不支持数组(或任何其他集合)作为参数,仅支持普通列表(您使用 ToInSql 方法生成的列表),对于 PostgreSQL,您需要使用 @987654323 @ 运算符,像这样:

SELECT manufacturer, model, year, AVG(price) as averageprice, AVG(miles) as averagemiles, COUNT(*) as count
FROM products
WHERE manufacturer = ANY(@manufacturers)
AND model = ANY(@models)
AND year = ANY(@years)
GROUP BY manufacturer, model, year

【讨论】:

  • 我收到一个错误:Npgsql.PostgresException (0x80004005): 22P03: invalid array flags;有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 2016-10-30
  • 2013-05-03
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2015-09-26
相关资源
最近更新 更多