Dapper: Result from "SELECT COUNT(*) FROM TableName

31.9k Views Asked by At

I have the following code:

string sql = "SELECT COUNT(*) FROM " + tableName;
var rtn = DapperConnection.Query<int>(sql);

This works and bring back 1 record in the rtn variable. When I inspect the variable it seems to have 2 members, one is "[0]" and the other is "Raw View".

The member [0] is of type int and has the expected value, but I can't seem to get to that value in my code. This seems like a stupid question because I should be able to get to it, but can't. The latest try was the following:

int rtnCount = (int)rtn[0];

This however gave me a compiler error. How do I get to this value in my code?

2

There are 2 best solutions below

0
On

Use rtn.First() — it is an enumeration so that's the general way to get its first (and only in this case) item.

4
On

Please don't do this! It's fragile, and introduces a gaping sql injection vulnerability. If you can return your count for a given table with one line of very expressive code, and no vulnerability, why make it method?

Do this instead:

DapperConnection.ExecuteScalar<int>("SELECT COUNT(*) FROM customers");

// You will be happier and live longer if you avoid dynamically constructing 
// sql with string concat.