Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to iterate through a Dapper DynamicParameters object?

Tags:

dapper

I need to make a generic logger to record certain insert/update statements so that my testers can verify the data being inserted is correct.

My first thought was that I would just use a function that accepted DynamicParameters and I would foreach through the DynamicParameters to generate a string to list the parameter's name and value and make them easier to read for the testers.

Unfortunately, Dapper.DynamicParameters does not contain a public definition for "GetEnumerator"

Here is basic example of what I was hoping to do:

string myFormattedListofParameters = "";
foreach (var p in myDynamicParameters)
{
myFormattedListofParameters += p.Name + "=" + p.Value.ToString();
}
like image 381
SLoret Avatar asked May 08 '12 15:05

SLoret


2 Answers

Try:

            var sb = new StringBuilder();
            foreach (var name in p.ParameterNames)
            {
                var pValue = p.Get<dynamic>(name);
                sb.AppendFormat("{0}={1}\n", name, pValue.ToString());
            }
like image 128
Sam Saffron Avatar answered Sep 19 '22 12:09

Sam Saffron


    string ParametersToString(DynamicParameters parameters)
    {
        var result = new StringBuilder();

        if (parameters != null)
        {
            var firstParam = true;
            var parametersLookup = (SqlMapper.IParameterLookup)parameters;
            foreach (var paramName in parameters.ParameterNames)
            {
                if (!firstParam)
                {
                    result.Append(", ");
                }
                firstParam = false;

                result.Append('@');
                result.Append(paramName);
                result.Append(" = ");
                try
                {
                    var value = parametersLookup[paramName];// parameters.Get<dynamic>(paramName);
                    result.Append((value != null) ? value.ToString() : "{null}");
                }
                catch
                {
                    result.Append("unknown");
                }
            }

        }
        return result.ToString();
    }
like image 37
Alexey Avatar answered Sep 21 '22 12:09

Alexey