How do I build a dynamic sql query with Dapper.SqlBuilder and OrWhere

泪湿孤枕 提交于 2019-12-06 04:12:07

问题


I am attempting to build a dynamic Sql query for multiple search terms. I understand in general how to use the builder, but am not sure what to do in the loop since I actually need the @term to be different each time (I think). Not just in the query, but in the anonymous type as well to match.

I could use a string.Format in the query string, but not sure how to match it in the anonymous type?

public async Task<List<Thing>> Search(params string[] searchTerms)
{
    var builder = new SqlBuilder();
    var template = builder.AddTemplate("SELECT * /**select**/ from ThingTags /**where**/ ");

    for (int i = 0; i < searchTerms.Length; i++)
    {
        builder.OrWhere("value LIKE @term", new { term = "%" + searchTerms[i] + "%" });
    }
...
}

in the current form the query that gets created for terms "abc" "def" "ghi" is

CommandType: Text, CommandText: SELECT *  from ThingTags WHERE  ( value LIKE @term OR value LIKE @term OR value LIKE @term ) 

Parameters:
Name: term, Value: %ghi%

回答1:


Well here is one way to do the query building. I didn't realize that the parameters could be a Dictionary initially.

public async Task<List<Thing>> Search(params string[] searchTerms)
{
var builder = new SqlBuilder();
var template = builder.AddTemplate("SELECT * /**select**/ from ThingTags /**where**/ ");

    for (int i = 0; i < searchTerms.Length; i++)
    {
        var args = new Dictionary<string, object>();
        var termId = string.Format("term{0}", i.ToString());
        args.Add(termId, "%" + searchTerms[i] + "%");
        builder.OrWhere("value LIKE @" + termId, args);
    }
...
}


来源:https://stackoverflow.com/questions/37487201/how-do-i-build-a-dynamic-sql-query-with-dapper-sqlbuilder-and-orwhere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!