Dapper.net"其中......在"查询不适用于PostgreSQL

时间:2016-07-04 15:53:56

标签: c# .net postgresql dapper

以下查询始终会产生错误" 42601:语法错误位于或接近" $ 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})";
    }

1 个答案:

答案 0 :(得分:13)

PostgreSQL IN运算符不支持数组(或任何其他集合)作为参数,只支持普通列表(使用ToInSql方法生成的列表),对于PostgreSQL,您需要使用ANY运算符,如下所示:

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