How can I do a batch select in Dapper?

c# dapper sql sql-server-2008

Question

I have a table with a composite primary key of two columns. In Dapper .NET I am using .Query by passing in my select statement, along with an array of the parameters. I found out that dapper only expects a single object for parameters in SELECT statements, unlike Execute for INSERT and UPDATE, where I could do this:

var batchParams = new List<object>();
batchParams.add(new 
    {
    ID = 50,
    Lang = 40
    });
batchParams.add(new 
    {
    ID = 20,
    Lang = 31
    });

And then I could just pass in this array to my execute call. Essentially, I want to run multiple select statements (each will retrieve one row), and then get the result back as an array of results. Is this possible in dapper?

Expert Answer

It isn't built in, but you could probably add an extension method that does something like:

foreach(var val in input)
    foreach(var row in conn.Query<T>(sql, val))
        yield return row;

This could also probably be achieved via SelectMany in LINQ-to-Objects:

var  combined = batch.SeletMany(x => conn.Query<T>(sql, x));


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