を使用する方が簡単だと思いますDictionary(TKey, TElement)
private void QueryDatabase(string connectionString, string commandText, IDictionary<string, object> parameters)
{
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText = commandText;
command.Parameters.AddRange(parameters.Select(l => new SqlParameter(l.Key, l.Value)));
command.CommandType = CommandType.StoredProcedure;
connection.Open()
command.ExecuteNonQuery();
}
}
編集:
public interface IParameterizable
{
IEnumerable<SqlParameter> GetParameters();
}
public SqlParameterAttribute : Attribute
{
public string Name { get; set; }
}
public class InsertTradingAcctTransFrontParameters : IParameterizable
{
[SqlParameter( Name = "@mBatchName" )]
public int CollectionId { get; set; }
/* ... */
IEnumerable<SqlParameter> GetParameters()
{
// Validation for properties, etc...
if(0 > CollectionId) throw new MeaningfulException("CollectionId must be greater than 0");
yield return new SqlParameter(GetParameterName("CollectionId"), CollectionId);
}
private string GetParameterName(string propertyName)
{
var attribute = GetType().GetProperty(propertyName).GetCustomAttributes(typeof(SqlParameterAttribute), false).SingleOrDefault();
if(attribute == null) throw new NotImplementedException(string.Format("SqlParameter is not defined for {0}", propertyName);
return ((SqlParameterAttribute)attribute).Name;
}
}
次に、クエリ方法を変更できます。
private void QueryDatabase(string connectionString, string commandText, IParameterizable parameters)
{
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText = commandText;
command.Parameters.AddRange(parameters.GetParameters());
command.CommandType = CommandType.StoredProcedure;
connection.Open()
command.ExecuteNonQuery();
}
}
この時点で、かなり再利用可能です。