How to limit parameters passed using Dapper's DynamicParameter constructor

asp.net c# dapper

Question

Using the Dapper DynamicParameters constructor, is there a way to exclude certain parameters from being included. For example, say I have the following entity,

public class EntityA
{
    public string Method1 { get; set; }
    public string Method2 { get; set; }
    public string Method3 { get; set; }
}

and I am calling a stored procedure that only has Method1 and Method2 as parameters, can I have the DynamicParameters method only pass the those two parameters and skip the third parameter? For my live example, I have alot more properties for my entity and would rather use an exclude scenario than specify parameter by hand.

Accepted Answer

The simplest option here is an anonymous projection - this can be done for either the argument object itself, or to the parameter to DynamicParameters if you need to add additional custom parameters; for example:

conn.Execute(sql, new { obj.Foo, obj.Bar });

or:

var args = new DynamicParameters(new { obj.Foo, obj.Bar });
// not shown: add some more custom parameters
conn.Execute(sql, args);

Popular Answer

You can use an extension method like the following to generate dynamic parameters. In a case like mine, where i have a Large number of parameters, it saves a little time.

public static class ParameterExtensions
{
    public static DynamicParameters ConvertToDynamicParameters<T>(this T incoming)
    {
      DynamicParameters dynamicParameters = new DynamicParameters();
      foreach (PropertyInfo property in incoming.GetType().GetProperties())
      {
        object value = GetPropValue(incoming, property.Name);
        if (value != null) dynamicParameters.Add(property.Name, value);
      }
      return dynamicParameters;
    }

    private static object GetPropValue(object src, string propName)
    {
      return src.GetType().GetProperty(propName)?.GetValue(src, null);
    }
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why