我有一个带有很多方法的 dal 层,它们都调用存储过程,一些返回列表(所以使用SqlDataReader
),其他的只有一个特定的值。
我有一个辅助方法可以创建SqlCommand
:
protected SqlCommand CreateSprocCommand(string name, bool includeReturn, SqlDbType returnType)
{
SqlConnection con = new SqlConnection(this.ConnectionString);
SqlCommand com = new SqlCommand(name, con);
com.CommandType = System.Data.CommandType.StoredProcedure;
if (includeReturn)
com.Parameters.Add("ReturnValue", returnType).Direction = ParameterDirection.ReturnValue;
return com;
}
现在我的平均(过度简化)方法体看起来像:
SqlCommand cmd = CreateSprocCommand("SomeSprocName"); //an override of the above mentioned method
try {
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader()) {
//some code looping over the recors
}
//some more code to return whatever needs to be returned
}
finally {
cmd.Connection.Dispose();
}
有没有办法重构它,这样我就不会失去我的辅助功能(它会做很多其他重复的工作),而且还能使用using
?