【发布时间】:2009-05-26 08:21:14
【问题描述】:
我有一个 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?
【问题讨论】:
标签: c# using sqlconnection sqlcommand