31

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?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
user2975847
  • 379
  • 1
  • 4
  • 9

2 Answers2

65

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.
Sasino
  • 134
  • 2
  • 11
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
  • 3
    I take it that "Please don't do this!" does not refer to your own answer, but the example in the original question (?) – Phil May 25 '18 at 11:27
  • 2
    Ha! Never thought of that :-) I'll be clearer the next time. – bbsimonbb May 25 '18 at 14:57
  • 1
    It's fine to do this as long as you have complete control over the table name variable. You don't want to do this with user input, though. – eltiare Jul 17 '18 at 23:27
  • 1
    Opinions vary. Personally I can't believe we ever attacked SQL with string methods. It's just aberrant, but it's an industry wide abberation - you don't need to take this personnaly. According to me, [this](https://marketplace.visualstudio.com/items?itemName=bbsimonbb.QueryFirst) is how we should talk to databases :-) – bbsimonbb Jul 18 '18 at 07:19
6

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

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
MiMo
  • 11,793
  • 1
  • 33
  • 48