如何在循环中添加dapper查询参数

时间:2019-04-04 10:17:44

标签: asp.net-core dapper

在循环中为dapper添加查询参数时,如下所示:

if (model.UserGroupId != null && model.UserGroupId.Count>0)
{
    var list = model.UserGroupId;
    sql += " and ( CHARINDEX(','+@group_id+',',','+mem.group_id+',')>0 ";
    paras.Add("group_id", list[0].Trim());
    for (var i = 1; i < list.Count(); i++)
    {
        string data = "@group_id" + i;
        sql += " or CHARINDEX('," + data+ ",',','+mem.group_id+',')>0 ";
        paras.Add(data, list[i].Trim());
    }
    sql += " )";
}

它不报告错误,但是查询结果不正确。由于无法搜索数据,因此无法使用动态@。我该如何解决这个问题?

如果我使用它,它可以正确搜索:

if (model.UserGroupId != null && model.UserGroupId.Count > 0)
{
    var list = model.UserGroupId;
    sql += " and ( CHARINDEX(','+@group_id+',',','+mem.group_id+',')>0 ";
    paras.Add("group_id", list[0].Trim());
    for (var i = 1; i < list.Count(); i++)
    {
        //  string data = "@group_id" + i;
        sql += " or CHARINDEX('," + list[i].Trim() + ",',','+mem.group_id+',')>0 ";
        // paras.Add(data, list[i].Trim());
    }
    sql += " )";
}

但是它有SQL注入问题。

1 个答案:

答案 0 :(得分:0)

           var list = model.UserGroupId;
            sql += " and ( CHARINDEX(','+@group_id+',',','+mem.group_id+',')>0 ";
            paras.Add("group_id", list[0].Trim());
            for (var i = 1; i < list.Count(); i++)
            {
               **sql += " or CHARINDEX(','+@group_id"+i+"+',',','+mem.group_id+',')>0 ";
                paras.Add("@group_id" + i, list[i].Trim());**
            }
            sql += " )";

它可以正确搜索