Automatically Discover and Assign Parameter with Values to a Stored Procedure Call in C#


I'm sure most programmers have run across a situation wherein they have to pass  a lot of parameters to a stored procedure call in C#. Instead of manually typing each parameter in and assigning a value, why not develop a way to automatically discover the parameter, add it to the parameter list of the command object and assign the corresponding value from an entity or model.

Here's my implementation using extension method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
        /// <summary>
        /// Automatically assigns parameters to Command.Parameter Collection from List of parameter names
        /// </summary>
        /// <param name="that">Command object being extended</param>
        /// <param name="model">Expando model</param>
        /// <param name="conn">sQLConnection used to get connectionstring</param>
        public static void AssignParameters(this SqlCommand that, ExpandoObject model, SqlConnection conn)
        {
            List<string> paramNames = DiscoverParameters(that, conn.ConnectionString);
            foreach (string paramName in paramNames)
            {
                if (model.ToList().Exists(x => ("@" + x.Key.ToUpper()) == paramName.ToUpper()))
                {
                    var param = model.ToList().Find(x => ("@" + x.Key.ToUpper()) == paramName.ToUpper());
                    that.Parameters.AddWithValue(paramName, param.Value ?? DBNull.Value);
                }
            }
        }
        /// <summary>
        /// Automatically discover parameter required by a given Store Proceducre name.
        /// </summary>
        /// <param name="cmd">SQL Command used to get the Command text</param>
        /// <param name="connStr">Connection String</param>
        /// <returns></returns>
        private static List<string> DiscoverParameters(SqlCommand cmd, string connStr)
        {

            PersistenceManager<List<string>> paramNamesPM = new PersistenceManager<List<string>>(PersistIn.Application, cmd.CommandText, 365);
            List<string> parameterNames;
            //check if parameter list is already persisted for the sp name.
            parameterNames = (paramNamesPM.Exists()) ? paramNamesPM.Get() : new List<string>();

            if (parameterNames == null || parameterNames.Count == 0)
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    SqlCommand command = conn.CreateCommand();
                    command.CommandText = cmd.CommandText;
                    command.CommandType = cmd.CommandType;
                    SqlCommandBuilder.DeriveParameters(command);
                    foreach (SqlParameter param in command.Parameters)
                    {
                        parameterNames.Add(param.ParameterName);
                    }
                    paramNamesPM.Add(parameterNames);
                }
            }
            return parameterNames;

        }

In the code above I used an ExpandoObject as the entity/model where the Parameter Values will be taken from, We'll discuss the ExpandoObject and the PersistenceManager on a different article for now let's focus on how we took the parameter list from the SP,

There's an object called SQLCommandBuilder we can use to extract the parameter from a specific SP, We can call the DeriveParameter method to retrieve all the parameters and add it to our List of string variable.

In the AssignParameter extension we iterated on the content of the List of Parameter Names and mapped the corresponding value from the Entity Object which is the Expando Model.

Hope you find this useful, happy coding.




Comments

Popular posts from this blog

Serializing JSON string to ExpandoObject

XML to ExpandoObject using Recursion in C#