How to return intger value by request object using dapper

In the method below, I am trying to return an intger that is returned by a stored procedure, it returns a value of 0 or greater than zero. In my understanding, when the data is returned, it will be a dictionary (not sure) when I try to return an integer. How can i achieve this. The code below is incomplete, and the code in the comment is what I did at the beginning, and I realized that I could rewrite the same code in a very simple way. I left them both, so I'm wrong, someone can fix me.

public int Exists(string plan) { using (var connection = new SqlConnection(Connection)) { connection.Open(); var parameters = new DynamicParameters(); //parameters.Add("@Plan", plan, DbType.String, //ParameterDirection.Input, null); //I guess I can directly pass param but not sure how ?? var data=connection.Query("storeProcmem_Plan", new{ ? ?}, CommandType.StoredProcedure); //how to return an integer int myvalue= data ??? connection.Close(); return Convert.ToInt32(data); 
+7
c # dapper
source share
1 answer

Assuming your parameters are fixed (usually intended for stored procedures), the main time you need DynamicParameters is that you generate SQL on-the = fly to match a complex flexible query) - then the aspect of the parameter is just as simple :

 new { Plan = plan } 

In this case, a function of an anonymous type of the compiler is used to determine that the parameter must have the name Plan , have the type string and have a value taken from the Plan variable.

If we assume that the stored procedure select results (rather than return , which must be encoded separately) on one line, then the easiest way to read this is:

 var myvalue = connection.Query<int>("storeProcmem_Plan", new { Plan = plan }, CommandType.StoredProcedure).First(); 

General and non-general API switches between typed results and dynamic results - both are used, but <int> seems appropriate here. .First() is a standard LINQ operation that translates from IEnumerable<T> to T by selecting the first value (and throwing an exception if there was none) - you can also use Single() , FirstOrDefault() or SingleOrDefault() in depending on the exact semantics you want.

For completeness, if you used a non-generic API, you need to know the column name - basically it will be:

 dynamic row = connection.Query("storeProcmem_Plan", new { Plan = plan }, CommandType.StoredProcedure).First(); int myvalue = row.ColumnName; 
+12
source share

All Articles