c# – Dapper.net“where … in”查询不适用于PostgreSQL

前端之家收集整理的这篇文章主要介绍了c# – Dapper.net“where … in”查询不适用于PostgreSQL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下查询始终生成错误“42601:语法错误在或接近”$1“
”.
  1. connection.Query<CarStatsProjection>(
  2. @"select manufacturer,model,year,AVG(price) as averageprice,AVG(miles) as averagemiles,COUNT(*) as count
  3. from products
  4. where manufacturer IN @manufacturers
  5. AND model IN @models
  6. AND year IN @years
  7. group by manufacturer,year",new { manufacturers = new[] { "BMW","AUDI" },models = new[] { "M4","A3" },years = new[] { 2016,2015 } });

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

  1. public static string ToInsql(this IEnumerable<object> values)
  2. {
  3. var flattened = values.Select(x => $"'{x}'");
  4. var flatString = string.Join(",",flattened);
  5.  
  6. return $"({flatString})";
  7. }

解决方法

Postgresql IN运算符不支持数组(或任何其他集合)作为参数,只支持普通列表(使用ToInsql方法生成的列表),对于Postgresql,您需要使用ANY运算符,如下所示:
  1. SELECT manufacturer,COUNT(*) as count
  2. FROM products
  3. WHERE manufacturer = ANY(@manufacturers)
  4. AND model = ANY(@models)
  5. AND year = ANY(@years)
  6. GROUP BY manufacturer,year

猜你在找的C#相关文章