Dapper로 저장 프로 시저를 호출하는 방법이 있습니까?


205

stackoverflow.com에 대한 Dapper Micro ORM 의 결과에 깊은 인상을 받았습니다 . 나는 새로운 프로젝트를 위해 그것을 고려하고 있지만 때로는 내 프로젝트에 저장 프로 시저가 필요하고 웹에서 많이 검색하지만 저장 프로 시저로 아무것도 찾지 못하는 것에 대해 한 가지 우려가 있습니다. Dapper가 저장 프로 시저와 작동하게하는 방법이 있습니까?

가능하다면 제게 알려주세요.


자세한 내용은 여기를 참조하십시오 stackoverflow.com/questions/5957774/…
— Majedur Rahaman

답변:


356

간단한 경우에는 다음을 수행 할 수 있습니다.

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를 사용할 수 있지만 더 복잡합니다.


1
ReturnValue 방향의 매개 변수를 먼저 정의해야합니까?
— Endy Tjahjono

3
@Sam Saffron .Output과 .ReturnVlaue의 차이점은 무엇입니까?
— 영원한 시간

샘, 이것이 SPROC의 결과 세트를 허용합니까?
— Brad

2
쿼리 결과 집합과 출력 매개 변수 값을 프로 시저에서 가져 오는 시나리오가 있습니다. 내가 사용하는 경우 cnn.Query<MyType>어떻게 나는 시저의 출력 매개 변수의 값을받을 수 있나요?
— Murali Murugesan

두 번째 (팬시) 솔루션은 하나 이상의 저장 프로 시저 매개 변수에 대해 null 값을 전달해야하는 경우에도 유용합니다.
— Ricardo Sanchez

13

대답은 사용해야하는 저장 프로 시저의 기능에 달려 있다고 생각합니다.

결과 세트를 리턴하는 스토어드 프로시 저는 Query; 결과 세트를 리턴하지 않는 스토어드 프로시 저는 Execute두 경우 모두-를 사용 EXEC <procname>하여 SQL 명령 (및 필요에 따라 입력 매개 변수 포함)을 사용하여 실행할 수 있습니다 . 자세한 내용은 설명서 를 참조하십시오.

개정 2d128ccdc9a2부터는OUTPUT 매개 변수에 대한 기본 지원이없는 것으로 보입니다 . 이를 추가하거나 QueryTSQL 변수를 선언하고 SP 수집 OUTPUT매개 변수를 로컬 변수로 실행 한 후 결과 세트로 리턴 하는보다 복잡한 명령을 구성 할 수 있습니다 .

DECLARE @output int

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

SELECT @output AS output1

17
출력 매개 변수에 대한 지원이 추가되었습니다. 최신 체크인 참조
— Sam Saffron

6
@ Sam-그것이 바로 서비스라고 부르는 것입니다!
— Ed Harper

6

다음은 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");

2

위와 동일, 조금 더 자세하게

.Net Core 사용

제어 장치

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 Microsoft.EntityFrameworkCore;
using Dapper;
using System.Data;
using System.Data.SqlClient;

왜 사용 Microsoft.EntityFrameworkCore합니까? DAL 에서는 Dapper 만 사용 합니까?
— PreguntonCojoneroCabrón

@ PreguntonCojoneroCabrón 필요하지 않습니다. 방금 모든 것을 붙여 넣었습니다
— Arun Prasad ES

EventCategory에 대한 샘플 행?
— Kiquenet

@ArunPrasadES에서 PreguntonCojoneroCabrón 포인트까지 문제를 해결하려는 사람들을 혼란스럽게하므로 불필요한 코드를 정리하고 제거하십시오. Visual Studio 및 Resharper에는 이러한 사용 정리를 수행하는 기능이 있습니다.
— Cubicle.Jockey

1

다중 리턴 및 다중 매개 변수

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

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

    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;
}

제품 검색 샘플 ? 2 개의 커서를 반환합니까?
— PreguntonCojoneroCabrón

0
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();
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.