2017-09-05 5 views
2

私のprocを呼び出し、返されたデータをデータセットに入れるために、次のメソッドを書いた。DapperでSQL procを呼び出す

public class GetDataFromProc 
{ 
    string constr; 
    public DataSet CallProcToDataSet(string procName) 
    { 
     DataSet ds = new DataSet(); 

     constr = ConfigurationManager.ConnectionStrings["DataBase"].ConnectionString; 

     using (SqlConnection con = new SqlConnection(constr)) 
     { 

      using (SqlCommand cmd = new SqlCommand(procName)) 
      { 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.Connection = con; 


       using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) 
       { 
        sda.Fill(ds); 
       } 
      } 
    } 
    return ds; 
} 

私がしたいのは、Dapper NuGetパッケージを利用することです。ドキュメントを通じて確認し、私は例procを呼び出しラインを見ることができ、次のとおりです。

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

はしかし、私は上記の例に私の方法を変換するための最良の方法がどうなるかわかりません。 Dapperの経験が豊富な人が私を助けてくれますか?

答えて

1
// Declare a model, with a property/field for every column 
// that you care about from your Result 
public class YourModel { 

    public int Id {get;set;} 
    // Whatever other columns your result has... 
} 



public class GetDataFromProc 
{ 
    string constr; 
    public IEnumerable<YourModel> CallProcToDataSet(string procName) 
    { 
     constr = ConfigurationManager.ConnectionStrings["DataBase"].ConnectionString; 

     using (SqlConnection con = new SqlConnection(constr)) 
     { 
      // If you expect only one row 
      var result = cnn.Query<YourModel>(procName, new { anyParametersYouHave = theirValue }, commandType: CommandType.StoredProcedure).SingleOrDefault(); 

      // If you expect more than one row and want a collection 
      var results= cnn.Query<YourModel>(procName, new { anyParametersYouHave = theirValue }, commandType: CommandType.StoredProcedure).ToList(); 

     } 
    } 
} 
関連する問題