Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 203
user2975847 Avatar asked Dec 16 '16 22:12

user2975847


People also ask

What does dapper execute return?

Dapper provides the Execute method (and its async equivalent) for commands that are not intended to return resultsets i.e. INSERT , UPDATE and DELETE commands. The Execute method returns an int , representing the number of rows affected by the successful completion of the command.

What is DynamicParameters in dapper C#?

The DynamicParameters type provides an Add method, enabling you to pass explicit parameters, specifying the datatype, direction and size: var parameters = new DynamicParameters(); var customerId = "ALFKI"; parameters. Add("@CustomerId", customerId, DbType.

Can I use dapper in .NET core?

Using Dapper Queries in ASP.NET Core Web API Then inside the using statement, we use our DapperContext object to create the SQLConnection object (or to be more precise an IDbConnection object) by calling the CreateConnection method.


1 Answers

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. 
like image 120
bbsimonbb Avatar answered Sep 24 '22 05:09

bbsimonbb