Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper query with list of parameters

I am trying to run a query with Dapper with a known set of parameters, but with a list of values for those parameters. A simple example of what I am trying to do would be:

DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddHours(-24);

string query = "select COUNT(*) from Test where Status = @Status AND DateCreated <= @Hour;";
var stuff = con.Query(query, (startDate).ByHourTo(endDate).Select(hour => new
{
     Status = 1,
     Hour = hour,
}));

Dapper throws an exception with 'Parameter '@Status' must be defined'. I know Dapper can process lists of parameters when doing bulk inserts and updates, but can it not do this for selects?

like image 564
Jarrod Avatar asked Nov 08 '12 15:11

Jarrod


People also ask

How do you pass multiple parameters in dapper query?

To use the dynamic parameters you have to set each parameter in the stored procedure, so you will have to loop through the list and add each property to the coresponding parameter.

What are dynamic parameters in dapper?

Fastest Dapper Plus Extensions The dynamic parameters allow you to specify parameters when you need to send parameters into a stored procedure or an SQL Statment. You can also use the anonymous type method that we have used in the previous articles.

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.

What is QueryMultipleAsync?

QueryMultipleAsync. This method runs multiple queries simultaneously and binds the result via a grid reader. The reader can be strongly typed in C#, which returns a list of enumerable objects. This works like QueryAsync , except it runs multiple queries.


1 Answers

Try this:

List<string> names = new List<string> { "Bob", "Fred", "Jack" };
string query = "select * from people where Name in @names";
var stuff = connection.Query<ExtractionRecord>(query, new {names});
like image 97
D'Arcy Rittich Avatar answered Sep 22 '22 09:09

D'Arcy Rittich