我相信使用 a 会更容易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();
}
}
在这一点上,它是非常可重用的。