How to get the first child value using dapper (typically querying count(*) as the only result)

c# dapper orm sql

Question

I want to implement some function like this:

public static string GetResult(string sql) {
    // TODO: 
    // result = connection.Query(....);
    // return result.FirstRow().FirstChild().ToString();
}

And call like this:

string myName = GetResult("SELECT userName from tb_Users WHERE ID = 1");
// or
int totalRows = Convert.ToInt32(GetResult("SELECT count(*) FROM tb_List"));

How can I implement TODO section using Dapper ?

Accepted Answer

Dapper has ExecuteScalar[<T>] which can be used if you are reading one column, one row, one grid. So:

var name = connection.ExecuteScalar<string>("select 'abc'");
int count = connection.ExecuteScalar<int>("select 123");

There is also Query{First|Single}[OrDefault][<T>] for all the usual "sort of one row, multiple columns" scenarios.

A word of caution on your API: anything that only accepts a string of sql (and no separate parameters) makes me very nervous that you are about to cause sql injection problems.



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