How does Dapper support stored procedures
This article mainly introduces how Dapper supports stored procedures, the article is very detailed, has a certain reference value, interested friends must read it!
In Entity Framework, I explained how EF supports stored procedures. Similarly, Dapper also supports stored procedures, as long as you mark the use of stored procedures in the CommandType of the Query () method. Create the following stored procedure on the Users table:
CREATE proc sp_GetUserByUserName@UserName varchar (16) asbeginselect * FROM Users WHERE UserName=@UserNameendGO
The code to call the stored procedure is as follows:
Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.SqlClient;using System.Configuration;using System.Data;using Dapper;using DapperApplicationProcedure.Model;namespace DapperApplicationProcedure {class Program {static void Main (string [] args) {/ / connection string string conn = ConfigurationManager.ConnectionStrings ["AppConnection"] .ConnectionString Using (IDbConnection connection = new SqlConnection (conn)) {var query = connection.Query ("sp_GetUserByUserName", new {UserName = "Wind is clear"}, commandType: CommandType.StoredProcedure) / / output query.AsList () .ForEach (p = > {Console.WriteLine ("name:" + p.Username + ", mailbox:" + p.Email + ", address:" + p.Address);} Console.ReadKey ();}
Run the process:
Note: stored procedures that use only one parameter are demonstrated in the example, and the same is true if you have more than one parameter.
Download address of sample code: click here to download
Use Execute to execute stored procedures with output parameters
Create the stored procedure as follows:
CREATE proc procWithOutPara@num1 int,@num2 int,@sum int outputasbegin set @ sum=@num1+@num2endGO
The code for the dapper call stored procedure is as follows:
/ / dynamic type parameter DynamicParameters paras = new DynamicParameters (); paras.Add ("@ num1", 23); paras.Add ("@ num2", 45); paras.Add ("@ sum", 0, DbType.Int32, ParameterDirection.Output); / / indicates the output parameter, where the parameter type size is specified / / execute the stored procedure dbConnection.Execute ("procWithOutPara", paras, commandType: CommandType.StoredProcedure) / / get the value of the output parameter int sum = paras.Get ("@ sum"); / / 68 is all the content of the article "how Dapper supports stored procedures". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!