Update
I know this is a very old question (and in fact, I came across it when looking for another old answer that I gave someone else to close as a duplicate), but I recently released a git hub project that answers this need . It minimizes code repetition when using ADO.Net, encapsulating Connection, Command, Parameters and DataAdapters.
If you want to try, I would be happy to know what you think about it.
First version
You can use a helper class to encapsulate sql parameters and create a single method for processing all data set populations as follows:
Helper Class:
private class SqlParamDefinition { public SqlParamDefinition(string name, SqlDbType dbType, object value) { this.Name = name; this.DbType = dbType; this.Value = value; } public string Name { get; } public SqlDbType DbType { get; } public object Value { get; } }
Run the method (based on the method you posted):
public DataSet ExecuteSelectProcedure(string procedeureName, params SqlParamDefinition[] parameters) { var ds = new DataSet(); using (var con = new SqlConnection(DatabaseConnectionString)) { using (var cmd = new SqlCommand(procedeureName, DbConn.objConn)) { cmd.CommandType = CommandType.StoredProcedure; for(int i = 0; i < parameters.Length; i++) { var param = parameters[i]; cmd.Parameters.Add(new SqlParameter(param.Name, param.DbType).Value = param.Value); } try { con.Open(); var objDataAdapter = new SqlDataAdapter(); objDataAdapter.SelectCommand = cmd; objDataAdapter.Fill(ds); con.Close(); } catch (Exception ex) {
Call example:
var parameters = new SqlParamDefinition[] { new SqlParamDefinition("@Param1", SqlDbType.VarChar, "value1"), new SqlParamDefinition("@Param2", SqlDbType.VarChar, "value2"), new SqlParamDefinition("@Param3", SqlDbType.Int, 123), }; var ds = ExecuteSelectProcedure("Strong procedure name", parameters);
Zohar peled
source share