Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper Call stored procedure and map result to class

I have a T-SQL stored procedure:

CREATE PROCEDURE [dbo].[GetRequestTest] 
        @RequestId UNIQUEIDENTIFIER
AS
BEGIN
    SELECT 
        Request.Amount,
        Request.Checksum 
    FROM 
        Request 
    WHERE
        RequestId = @RequestId
END

C# mapping class:

public class CustomTest : Itest
{
    public decimal Amount {get;set;}
    public string Checksum { get; set; }
}

I'm calling trying to invoke stored procedure by using Dapper:

public void Load(CustomTest obj, Guid RequestId)
{
    using (var con = base.GetClosedConnection())
    {
        con.Open();

        var p = new DynamicParameters();
        p.Add("@RequestId", dbType: DbType.Guid, direction: ParameterDirection.Input);               

        var result = con.ExecuteReader("[dbo].[GetRequestTest]", param: p, commandType: CommandType.StoredProcedure);

        while (result.Read())
             obj.Amount = (decimal)result["Amount"];
    }            
}

But result is null

I tried to call to put SQL statement from stored procedure directly into C# code - and it works fine, but it doesn't work with stored procedure.

Any ideas - how to make it work?

like image 438
Max Iakovliev Avatar asked Jul 10 '15 06:07

Max Iakovliev


2 Answers

You call wrong method:

public void Load(CustomTest obj, Guid RequestId)
{
    using (var con = base.GetClosedConnection())
    {
        con.Open();                

        //result is list of CustomTest
        var result = db.Query<CustomTest>("GetRequestTest", new {RequestId},
                         commandType: CommandType.StoredProcedure);
    }            
}

How to use dapper: https://github.com/StackExchange/dapper-dot-net

like image 166
Nguyen Kien Avatar answered Sep 28 '22 07:09

Nguyen Kien


using (var con = base.GetClosedConnection())
{
    var result = conn.Query<CustomTest>("exec [dbo].[GetRequestTest] @id", new {Id = RequestId});
}

Column names stored procedure or query returns should be same as CustomTest`s property names (e.g. Amount, Checksum). As result you will receive IEnumerable filled with appropriate data.

like image 27
Alex Erygin Avatar answered Sep 28 '22 07:09

Alex Erygin