1

How can I use dynamic queries in C# ? From what I've searched its similiar to when we use SqlCommand with parameters to prevent sql injection(example below).

using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
        {
            DB_CONNECTION.Open();
            string sqlquery = "UPDATE table SET Name =@Name, IsComplete=@IsComplete WHERE Key =@Key;";
            int rows = 0;
            using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
            {
                SQLiteParameter[] tableA = { new SQLiteParameter("@Key", todo.Key), new SQLiteParameter("@Name", table.Name), new SQLiteParameter("@IsComplete", table.IsComplete) };
                command.Parameters.AddRange(tableA);
                rows = command.ExecuteNonQuery();
            }
            DB_CONNECTION.Close();
            return (rows);
        }

I'm new to c# and i wondering how can I make this work, thanks in advance.

Esteves
  • 35
  • 8
  • 4
    It might be better to ask how to solve the problem that you think dynamic queries will solve. – spender Apr 21 '16 at 08:36
  • I have a project where I have to manage data from a ERP and I was told to use dynamic queries to edit the data – Esteves Apr 21 '16 at 09:03
  • I've posted an answer below to suggest how to augment the example above to build up a dynamic query based on whether a particular variable is an empty string or white-space. I've also written a more modern example using Entity Framework. – Aaron Newton Apr 21 '16 at 12:23

1 Answers1

0

Basically just build up the string sqlQuery based on a set of conditions and ensure that the appropriate parameters have been set. For example, here is some psuedo-C# (not tested for bugs):

//Set to true, so our queries will always include the check for SomeOtherField.
//In reality, use some check in the C# code that you would want to compose your query.
//Here we set some value we want to compare to.
string someValueToCheck = "Some value to compare";

using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
{
    DB_CONNECTION.Open();
    string sqlquery = "UPDATE MyTable SET Name =@Name, IsComplete=@IsComplete WHERE Key =@Key";

    //Replace this with some real condition that you want to use.
    if (!string.IsNullOrWhiteSpace(someValueToCheck))
    {
        sqlquery += " AND SomeOtherField = @OtherFieldValue"
    }

    int rows = 0;
    using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
    {
        //Use a list here since we can't add to an array - arrays are immutable.
        List<SQLiteParameter> tableAList = {
            new SQLiteParameter("@Key", todo.Key),
            new SQLiteParameter("@Name", table.Name),
            new SQLiteParameter("@IsComplete", table.IsComplete) };

        if (!string.IsNullOrWhiteSpace(someValueToCheck)) {
            //Replace 'someValueToCheck' with a value for the C# that you want to use as a parameter.
            tableAList.Add(new SQLiteParameter("@OtherFieldValue", someValueToCheck));
        }

        //We convert the list back to an array as it is the expected parameter type.
        command.Parameters.AddRange(tableAList.ToArray());
        rows = command.ExecuteNonQuery();
    }
    DB_CONNECTION.Close();
    return (rows);
}

In this day and age it would probably be worth looking into LINQ to Entities, as this will help you to compose queries dynamically in your code - for example https://stackoverflow.com/a/5541505/201648.

To setup for an existing database - also known as "Database First" - see the following tutorial: https://msdn.microsoft.com/en-au/data/jj206878.aspx

You can skip step 1 since you already have a database, or do the whole tutorial first as practice.

Here is some psuedo-C# LINQ code to perform roughly the same update as the previous example:

//The context you have setup for the ERP database.
using (var db = new ERPContext()) 
{ 

    //db is an Entity Framework database context - see 
    //https://msdn.microsoft.com/en-au/data/jj206878.aspx
    var query = db.MyTable
        .Where(c => c.Key == todo.Key);

    if (!string.IsNullOrWhiteSpace(someValueToCheck))
    {
        //This where is used in conjunction to the previous WHERE,
        //so it's more or less a WHERE condition1 AND condition2 clause.
        query = query.Where(c => c.SomeOtherField == someValueToCheck);
    }

    //Get the single thing we want to update.
    var thingToUpdate = query.First();

    //Update the values.
    thingToUpdate.Name = table.Name;
    thingToUpdate.IsComplete = table.IsComplete;

    //We can save the context to apply these results.
    db.SaveChanges();

}

There is some setup involved with Entity Framework, but in my experience the syntax is easier to follow and your productivity will increase. Hopefully this gets you on the right track.

LINQ to Entites can also map SQL stored procedures if someone one your team objects to using it for performance reasons:

https://msdn.microsoft.com/en-us/data/gg699321.aspx

OR if you absolutely ust compose custom queries in the C# code this is also permitted in Entity Framework:

https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx

Community
  • 1
  • 1
Aaron Newton
  • 2,124
  • 1
  • 28
  • 31