Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create arguments for a Dapper query dynamically

Tags:

c#

.net

dapper

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); 
like image 880
Cogslave Avatar asked Feb 28 '12 12:02

Cogslave


People also ask

What is dynamic parameters in dapper?

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>

How to use Dynamic parameters in c#?

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.

What is DynamicParameters?

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.


1 Answers

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); 
like image 182
Marc Gravell Avatar answered Oct 11 '22 23:10

Marc Gravell