I have a web API I'm building in C#. This web API is used as a front end to query a SQL database. I am using SqlKata as the engine to perform the querying. When generating a WHERE clause, the SqlKata documentation states the following:
Multiple fields
If you want to filter your query against multiple fields, pass an object that represents col/values.
var query = new Query("Posts").Where(new {
Year = 2017 ,
CategoryId = 198 ,
IsPublished = true,
});
I want to be able to avoid hardcoding the WHERE clause, but rather base it on passed in querystrings. My idea was to add each querystring name and value to a Dictionary then somehow use the values of that Dictionary within the SqlKata .Where() clause. I thought maybe I could convert the Dictionary to the required anonymous object, but I can't get it to work. Any ideas folks on how to do this? So my url might be:
https://webapi.com.au/api?store=120&name=james
Dictionary: store=120 name=james
Query: var query = new query("Posts").Where(anonObject)
( anonObject would be {store=120,name=james} )
You don't need an anonymous object. Looking at the SqlKata docs, you can just build up the query by looping over the dictionary, something like this:
//Assuming the dictionary is something like Dictionary<string, object>
var query = new Query("Posts");
foreach(var element in dictionary)
{
query = query.Where(element.Key, element.Value);
}
var result = query.Get();
Note: Never even heard of SqlKata before so this is just from looking at the docs.