0

I have an MVC-Razor project, and I am obligated to make it without employing ORM. I use only SQL commands, and in the add(model) method for the DB controller I execute a query string command in this format:

string queryString =
                "INSERT INTO USERS VALUES(@EMAIL,@PAIS,@IDIOMA,@CODPROMO,@NOMBREUSU"+
                ",@PASS,@PIN,@TRATAMIENTO,@NOMBREPERS,@APELLIDOS,@FECHANAC,@DIRECCION,@NUMPISO"+
                ",@CP,@CIUDAD,@NIF,@NUMMOVIL,@SUBSCRIBIR,@CONDICIONES,@PRIVACIDAD)";

As you can see there are a lot of parameters to insert in the table. Then, I have to link those @parameters with command.Parameters.AddWithValue("@EMAIL",socio.Mail);

Is there any faster way to do all of this (something more dynamic, perhaps?) without all of that writing?

6
  • 5
    copy + paste i guess May 31, 2016 at 18:55
  • Assuming all the parameters are properties in a class you can use reflection to loop over the class and create the query string May 31, 2016 at 18:57
  • why don't you create a Stored procedure.. or create a Class that mimics the structure of your query or queries..
    – MethodMan
    May 31, 2016 at 18:59
  • You could write an extension method, but you would still have to provide the parameter names, of course.
    – code4life
    May 31, 2016 at 18:59
  • I dont know which answer to mark as the solution since they both work.@JaredStroeb game a more ORM oriented answer but explains exacly how to form the string from other hand @Rahul gave me a great answer too.Now what ? May 31, 2016 at 20:47

2 Answers 2

3

So any faster way to do this without all of that writing?

Yes, if this is what you have to do then consider refactoring your SQL code and pull it into a stored procedure(SP) and call that SP in your code instead. You can as well consider using a table type variable if you want to send the structured data.

2

Here is a quick example of reflection to build a query string. The idea is to have a class that mirrors the table's columns. The following code can be used to build an insert for any data model class. It will build the insert statement and fill in the parameters then execute the statement.

    public static void GenericSqlInsert(string connectionString, string table, Object model)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string commandText = "Insert into " + table + "Values(";
            SqlCommand command = new SqlCommand();
            PropertyInfo[] properties = model.GetType().GetProperties();

            foreach (PropertyInfo property in properties)
            {
                commandText += "@" + property.Name + ",";
                command.Parameters.AddWithValue("@" + property.Name, property.GetValue(model));
            }
            commandText = commandText.TrimEnd(',');
            commandText += ") ";

            try
            {
                command.Connection = connection;
                command.CommandText = commandText;

                connection.Open();

                Int32 rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine("RowsAffected: {0}", rowsAffected);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

I don't know if I would recommend this method but it is an interesting use of reflection.

Edited to reflect the suggestion of Alexei Levenkov

Edited to make the function more generic

7
  • Recommending SQL injection is not a good idea (especially without any warnings). Similar sample adding parameters would deserve upvotes instead. May 31, 2016 at 19:33
  • @Alexei Levenkov I made the changes to use sql query parameters. My initial answer did not reflect best practices. May 31, 2016 at 19:47
  • Looks good, make sure to add usage of parameters to command to build string similar to what OP showed. May 31, 2016 at 19:55
  • But then didn't you essentially create your own super-basic ORM?
    – dmeglio
    May 31, 2016 at 20:06
  • @dman2306 Now that I made it more generic it is essentially a super-basic ORM May 31, 2016 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.