Dapper源码拼接参数问题
线上分了N张表,多表查询sql使用where in方法。容易抛出参数已经定义的异常。例如:"Parameter 'sqlParams111' has already been defined."
问题代码例子:
//test_01表和test_11表只包含两个字段自增id和addtime try { using (var conn = new MySqlConnection(connStr)) { conn.Open(); var ids1 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; var ids2 = new List<int> { 1, 20, 18, 17 }; var sql = @" select addtime from test_01 where id in @sqlParams1 union all select addtime from test_11 where id in @sqlParams11"; var res = conn.Query<DateTime>(sql, new { sqlParams1 = ids1, sqlParams11 = ids2 }).ToList(); res.ForEach(s => Console.WriteLine(s)); Console.ReadKey(); } } catch (Exception ex) { throw; }
代码执行后抛出异常:"Parameter 'sqlParams111' has already been defined."
原因:
dapper自己拼接where in 里面的参数的时候,是后面数字++.
实际的sql:
select addtime from test_01 where id in (@sqlParams11,@sqlParams12,@sqlParams13,@sqlParams14,@sqlParams15,@sqlParams16,@sqlParams17,@sqlParams18,@sqlParams19,@sqlParams110,@sqlParams111)
union all
select addtime from test_11 where id in
(@sqlParams111,@sqlParams1120,@sqlParams11118,@sqlParams11117)
可以看到 sqlParams111 确实重复了
解决流程:
下载 dapper开源地址:https://github.com/StackExchange/Dapper issues:https://github.com/StackExchange/Dapper/issues/1636
直接本地添加项目 调试发现异常与拼接结果
把@sqlParams1和@sqlParams11 改成@sqlParams1_和@sqlParams11_解决