问题描述
在SQL WHERE
子句中使用Dapper参数时,该参数似乎区分大小写.然而,当我用字符串文字替换Dapper参数时,WHERE
子句不再区分大小写.我创建了一个简单的ASP.NET核心recipe example web API来帮助说明这个问题.
在这个配方示例中,我使用了一个PostgreSQL
数据库,并希望查询一个recipe table以按名称获取配方.我制作了citext
类型的name
列,这是一种不区分大小写的字符串类型.
数据库表
recipe
表说明:
+-------------+--------+-----------+----------+--------------------+
| Column | Type | Collation | Nullable | Default |
+-------------+--------+-----------+----------+--------------------+
| recipe_id | uuid | | not null | uuid_generate_v4() |
| name | citext | | not null | |
| description | text | | | |
+-------------+--------+-----------+----------+--------------------+
recipe
表的内容包括:
+--------------------------------------+--------------------+-----------------------------------------------------------+
| recipe_id | name | description |
+--------------------------------------+--------------------+-----------------------------------------------------------+
| 8f749e7a-e192-48df-91af-f319ab608212 | meatballs | balled up meat |
| f44c696f-a94a-4f17-a387-dd4d42f60ef8 | red beans and rice | yummy new orleans original |
| 82c5911b-feec-4854-9073-6a85ea793dc0 | pasta cereal | couscous and ground meat eaten with a spoon, like cereal! |
+--------------------------------------+--------------------+-----------------------------------------------------------+
查询方法
RecipeController
有一个GetByName
方法,该方法接受name
参数作为URI路径的一部分.GetByName
方法调用RecipeRepository
类的GetByNameAsync
方法,其中包含有问题的SQL语句:
public async Task<Recipe> GetByNameAsync(string name)
{
string sql = $@"
SELECT *
FROM {nameof(Recipe)}
WHERE {nameof(Recipe)}.{nameof(Recipe.name)} = @{nameof(name)}";
using (IDbConnection connection = Open())
{
IEnumerable<Recipe> recipes = await connection.QueryAsync<Recipe>(sql, new {name});
return recipes.DefaultIfEmpty(new Recipe()).First();
}
}
查询响应
如果我想按名称查询meatballs食谱,并将name
参数设置为"meatballs",我会得到以下响应:
{
"recipe_id": "8f749e7a-e192-48df-91af-f319ab608212",
"name": "meatballs",
"description": "balled up meat"
}
将name
参数设置为"Meatballs",我得到以下响应:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
"title": "Not Found",
"status": 404,
"traceId": "00-5e4e35d5cfec644fc117eaa96e854854-c0490c8ef510f3b1-00"
}
最后,如果我用字符串文字"Meatballs"替换Dapper name
参数:
public async Task<Recipe> GetByNameAsync(string name)
{
string sql = $@"
SELECT *
FROM {nameof(Recipe)}
WHERE {nameof(Recipe)}.{nameof(Recipe.name)} = 'Meatballs'";
using (IDbConnection connection = Open())
{
IEnumerable<Recipe> recipes = await connection.QueryAsync<Recipe>(sql, new {name});
return recipes.DefaultIfEmpty(new Recipe()).First();
}
}
我得到以下回应:
{
"recipe_id": "8f749e7a-e192-48df-91af-f319ab608212",
"name": "meatballs",
"description": "balled up meat"
}
Why is this Dapper parameter forcing case-sensitivity? And how can I get around this?