Is there a way to create parameters for a MySQLCommand
object before creating the actual object?
Currently I have to set up generated commands like this:
public static MySqlCommand User(MySqlConnection MySQL, User u)
{
var cmdVars = new List<string>();
const string cmd = "SELECT * FROM `schema`.`table` WHERE 1=1 AND ";
if (u.ID != null) cmdVars.Add("`ID` LIKE @0");
if (u.Username != null) cmdVars.Add("`Username` LIKE @1");
if (u.First != null) cmdVars.Add("`FirstName` LIKE @2");
if (u.Last != null) cmdVars.Add("`LastName` LIKE @3");
if (u.Phone != null) cmdVars.Add("`Phone` LIKE @4");
if (u.Extension != null) cmdVars.Add("`Extension` LIKE @5");
if (u.Email != null) cmdVars.Add("`Email` LIKE @6");
var MySqlCmd = new MySqlCommand(cmd + string.Join(" AND ", cmdVars), MySQL);
if (u.ID != null) MySqlCmd.Parameters.AddWithValue("@0", u.ID);
if (u.Username != null) MySqlCmd.Parameters.AddWithValue("@1", u.Username);
if (u.First != null) MySqlCmd.Parameters.AddWithValue("@2", u.First);
if (u.Last != null) MySqlCmd.Parameters.AddWithValue("@3", u.Last);
if (u.Phone != null) MySqlCmd.Parameters.AddWithValue("@4", u.Phone);
if (u.Extension != null) MySqlCmd.Parameters.AddWithValue("@5", u.Extension);
if (u.Email != null) MySqlCmd.Parameters.AddWithValue("@6", u.Email);
return MySqlCmd;
}
Which, although works fine, is gross to look at as more parameters are added and requires a user to create a new User object just to search by one value.
I considered switching to the method shown in this question, but in use with MySQLConnector it becomes overly complicated to manage the values and doesn't really do anything for improved readability.