简体   繁体   English

如何使用Dapper在C#中映射一个简单的存储过程?

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

My Stored Procedure just returns a string . 我的存储过程仅返回一个string Eg: This stored procedure returns "en-US" 例如:此存储过程返回"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: 我正在像这样使用Dapper

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

where my ModelClass is 我的ModelClass在哪里

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

But getting null . 但是变得null

Any ideas what am I missing here ? 有什么想法我在这里想念吗? (or is there any other method to call this ?) (或者是否有其他方法可以调用此方法?)

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 可能应该将属性结果命名为SP(值)返回的字段,但这会与保留关键字产生冲突

So, change the SP to rename the field returned as the property of your model 因此,更改SP以将返回的字段重命名为模型的属性

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 另外,我建议将代码更改为使用FirstOrDefault,以防您的SP找不到任何东西而您的代码将引发异常

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM