.net 有没有办法用Dapper调用存储过程?

ubbxdtey  于 2023-02-10  发布在  .NET
关注(0)|答案(6)|浏览(137)

我对stackoverflow.com的Dapper Micro ORM的结果印象深刻。我正在考虑我的新项目,但我有一个担心,有时我的项目需要有存储过程,我已经在网上搜索了很多,但没有找到任何存储过程。所以有没有办法让Dapper使用存储过程?
请让我知道,如果这是可能的,否则我不得不延长它在我的方式。

ac1kyiln

ac1kyiln1#

在简单的情况下,您可以:

var user = cnn.Query<User>("spGetUser", new {Id = 1}, 
        commandType: CommandType.StoredProcedure).First();

如果你想要一些更花哨的东西,你可以这样做:

var p = new DynamicParameters();
 p.Add("@a", 11);
 p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
 p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

 cnn.Execute("spMagicProc", p, commandType: CommandType.StoredProcedure); 

 int b = p.Get<int>("@b");
 int c = p.Get<int>("@c");

此外,您可以在批处理中使用exec,但这样做比较笨拙。

2o7dmzc5

2o7dmzc52#

我认为答案取决于您需要使用存储过程的哪些特性。
返回结果集的存储过程可以使用Query运行;不返回结果集的存储过程可以使用Execute运行-在这两种情况下(使用EXEC <procname>)都是作为SQL命令(必要时加上输入参数)。
2d128ccdc9a2版本开始,似乎没有对OUTPUT参数的本地支持;您可以添加此命令,或者构造一个更复杂的Query命令,该命令声明TSQL变量,执行SP并将OUTPUT参数收集到局部变量中,最后在结果集中返回这些参数:

DECLARE @output int

EXEC <some stored proc> @i = @output OUTPUT

SELECT @output AS output1
gwbalxhn

gwbalxhn3#

下面是从Store过程获取返回值的代码
存储过程:

alter proc [dbo].[UserlogincheckMVC]    
@username nvarchar(max),    
@password nvarchar(max)
as    
begin    
    if exists(select Username from Adminlogin where Username =@username and Password=@password)    
        begin        
            return 1  
        end    
    else    
        begin     
            return 0  
        end    
end

代码:

var parameters = new DynamicParameters();
string pass = EncrytDecry.Encrypt(objUL.Password);
conx.Open();
parameters.Add("@username", objUL.Username);
parameters.Add("@password", pass);
parameters.Add("@RESULT", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
var RS = conx.Execute("UserlogincheckMVC", parameters, null, null, commandType: CommandType.StoredProcedure);
int result = parameters.Get<int>("@RESULT");
5q4ezhmt

5q4ezhmt4#

同上,略详细
使用.Net核心
主计长

public class TestController : Controller
{
    private string connectionString;
  
    public IDbConnection Connection
    {
        get { return new SqlConnection(connectionString); }
    }

    public TestController()
    {
        connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
    }

    public JsonResult GetEventCategory(string q)
    {
        using (IDbConnection dbConnection = Connection)
        {
            var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
    commandType: CommandType.StoredProcedure).FirstOrDefault();

            return Json(categories);
        }
    }

    public class ResultTokenInput
    {
        public int ID { get; set; }
        public string name { get; set; }            
    }
}

存储过程(父子关系)

create PROCEDURE GetEventCategories
@keyword as nvarchar(100)
AS
    BEGIN

    WITH CTE(Id, Name, IdHierarchy,parentId) AS
    (
      SELECT 
        e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
        cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
      FROM 
        EventCategory e  where e.Title like '%'+@keyword+'%'
     -- WHERE 
      --  parentid = @parentid

      UNION ALL

      SELECT 
        p.EventCategoryID as Id, cast(p.Title + '>>' + c.name as varchar(max)) as Name,
        c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
      FROM 
        EventCategory p 
      JOIN  CTE c ON c.Id = p.parentid

        where p.Title like '%'+@keyword+'%'
    )
    SELECT 
      * 
    FROM 
      CTE
    ORDER BY 
      IdHierarchy

案例参考

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SocialStoriesCore.Data;
using Dapper;
using System.Data;
using System.Data.SqlClient;
rxztt3cl

rxztt3cl5#

具有多返回和多参数

string ConnectionString = CommonFunctions.GetConnectionString();
using (IDbConnection conn = new SqlConnection(ConnectionString))
{
    // single result
    var results = conn.Query(sql: "ProductSearch", 
        param: new { CategoryID = 1, SubCategoryID="", PageNumber=1 }, 
        commandType: CommandType.StoredProcedure);

    var salarydetails = reader.Read<dynamic>().ToList();

    // multiple result
    var reader = conn.QueryMultiple("ProductSearch", 
        param: new { CategoryID = 1, SubCategoryID = "", PageNumber = 1 }, 
        commandType: CommandType.StoredProcedure); 

    var userdetails = reader.Read<dynamic>().ToList(); // instead of dynamic, you can use your objects
    var salarydetails = reader.Read<dynamic>().ToList();
}

public static string GetConnectionString()
{
    // Put the name the Sqlconnection from WebConfig..
    return ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
kuarbcqp

kuarbcqp6#

public static IEnumerable<T> ExecuteProcedure<T>(this SqlConnection connection,
    string storedProcedure, object parameters = null,
    int commandTimeout = 180) 
    {
        try
        {
            if (connection.State != ConnectionState.Open)
            {
                connection.Close();
                connection.Open();
            }

            if (parameters != null)
            {
                return connection.Query<T>(storedProcedure, parameters,
                    commandType: CommandType.StoredProcedure, commandTimeout: commandTimeout);
            }
            else
            {
                return connection.Query<T>(storedProcedure,
                    commandType: CommandType.StoredProcedure, commandTimeout: commandTimeout);
            }
        }
        catch (Exception ex)
        {
            connection.Close();
            throw ex;
        }
        finally
        {
            connection.Close();
        }

    }
}

var data = db.Connect.ExecuteProcedure<PictureModel>("GetPagePicturesById",
    new
    {
        PageId = pageId,
        LangId = languageId,
        PictureTypeId = pictureTypeId
    }).ToList();

相关问题