【问题标题】:Check null for list parameter in Dapper在 Dapper 中检查列表参数是否为空
【发布时间】:2013-09-09 01:30:05
【问题描述】:

当参数类型是 IEnumerable 时,有没有办法检查 null?我知道 Dapper 会将列表参数转换为参数化查询,所以我怀疑这就是无法检查列表参数是否为空的原因,但我想知道是否有办法实现这种行为。

这个想法是做这样的事情:

select * from Table1 where (@ids IS NULL OR id in @ids)

现在查询抛出 SqlException 并显示以下消息:必须声明标量变量“@ids”。 ')' 附近的语法不正确。

【问题讨论】:

    标签: parameters dapper


    【解决方案1】:

    id in @ids 是一种被 dapper 识别并被视为扩展的模式 - 因此,根据您输入 ids 中的项目数量,这可能成为以下之一:

    (1 = 0) -- empty sequence
    (id = @ids_0) -- sequence with 1 element
    (id in (@ids_0, @ids_1, ...)) -- sequence with multiple elements
    

    因此,在扩展之后, 没有@ids 参数/变量 - 所以@ids IS NULL 不起作用。因此,我建议在您的情况下的最佳方法很简单:不要添加 tsql 的那部分。例如:

    var sql = new StringBuilder("select * from Table1");
    if(ids != null && ids.Any())
    {
        sql.Append(" where id in @ids");
    }
    var data = conn.Query<SomeType>(sb.ToString(), new { ids }).ToList();
    

    【讨论】:

    • 谢谢,我最终做到了。我还在考虑使用另一个参数 (@idsRef) 作为标志,例如: where (@idsRef=0 OR id in @ids)。
    • 我也有同样的问题,问了类似的问题 (@idsCount=0 OR id in @ids)
    【解决方案2】:
    where Id in @ids or 0=@listCount
    

    然后

    var data = conn.Query<SomeType>(sb.ToString(), new { ids, listCount=ids.Count }).ToList();
    

    【讨论】:

    • 非常感谢!
    • 干净优雅!
    • 这个解决方案在我的查询中完美运行,并且比接受的答案更干净。
    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2017-06-11
    相关资源
    最近更新 更多