I have a dictionary of values Eg "Name": "Alex"
Is there a way to pass this to Dapper as arguments for a query?
Here is an example showing what I want to do.
IDictionary<string, string> args = GetArgsFromSomewhere(); string query = "select * from people where Name = @Name"; var stuff = connection.Query<ExtractionRecord>(query, args);
DynamicParameters Bag. Dapper also provides a DynamicParameters class, which represents a "bag" of parameter values. You can pass an object to its constructor. Suitable objects include a Dictionary<string, object> : var dictionary = new Dictionary<string, object>
Dynamic Parameters In C# 4.0, a new type of parameters is introduced that is known as a dynamic parameter. Here the parameters pass dynamically means the compiler does not check the type of the dynamic type variable at compile-time, instead of this, the compiler gets the type at the run time.
Dynamic parameters allow you to create actions that are different every time they are performed. Dynamic parameters can be passed as arguments to most vizact actions. The value of these parameters is determined when the action is performed, and you can setup these parameters to change values every time.
Yes:
var dbArgs = new DynamicParameters(); foreach(var pair in args) dbArgs.Add(pair.Key, pair.Value);
Then pass dbArgs
in place of args
:
var stuff = connection.Query<ExtractionRecord>(query, dbArgs);
Alternatively, you can write your own class that implements IDynamicParameters
.
Note that if you are starting from an object (the usual approach with dapper), you can also use this template with DynamicParameters
as a starting point:
var dbArgs = new DynamicParameters(templateObject);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With