How to user dapper to map a simple stored procedure in c#?

My Stored Procedure just returns a string. Eg: This stored procedure returns "en-US"

CREATE PROCEDURE [dbo].[P_GetStringConfig](  
  @iCode CHAR(20))  
AS  
BEGIN  
  SET NOCOUNT ON  

  SELECT Value  
  FROM  T_SReq_Config WITH (NOLOCK)  
  WHERE Code = @iCode  

  IF @@ERROR <> 0  
  RETURN @@ERROR  

  RETURN 0  
END

I am using Dapper like this:

using (var connection = new SqlConnection(GetConnectionString()))
            {
                var result = connection.Query<ModelClass>(
                                                    "P_GetStringConfig",
                                                    new {@iCode = "MCode"},
                                                    commandType:     CommandType.StoredProcedure).First();
            }

where my ModelClass is

class ModelClass
{
  string result {get;set;}
}

But getting null.

Any ideas what am I missing here ? (or is there any other method to call this ?)

Upvotes: 1

Views: 1156

Answers (1)

Steve
Steve

Reputation: 216243

Probably you should have your property result named as the field returned by the SP (value) but this creates a conflict with a reserved keyword

So, change the SP to rename the field returned as the property of your model

CREATE PROCEDURE [dbo].[P_GetStringConfig](  
  @iCode CHAR(20))  
AS  
BEGIN  
  SET NOCOUNT ON  

  SELECT Value AS result
  FROM  T_SReq_Config WITH (NOLOCK)  
  WHERE Code = @iCode  

  IF @@ERROR <> 0  
  RETURN @@ERROR  

  RETURN 0  
END

Also, I suggest to change the code to use FirstOrDefault in case your SP doesn't find anything your code will raise an Exception

 var result = connection.Query<ModelClass>("P_GetStringConfig",
                                            new {@iCode = "MCode"},
                                            commandType:CommandType.StoredProcedure)
                                            .FirstOrDefault();

Upvotes: 2

Related Questions