Gid*_*don 1 c# using sqlcommand sqlconnection
我有一个带有许多方法的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;
}
Run Code Online (Sandbox Code Playgroud)
现在我的平均(过度简化)方法体看起来像:
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();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法重构这个,这样我就不会失去我的辅助函数(它会做很多其他重复的工作),但是能够使用using?
Jon*_*eet 13
一种方法是将其从改变返回的命令采取它使用命令的委托:
protected void ExecuteSproc(string name,
SqlDbType? returnType,
Action<SqlCommand> action)
{
using (SqlConnection con = new SqlConnection(this.ConnectionString))
using (SqlCommand com = new SqlCommand(name, con))
{
con.Open();
com.CommandType = System.Data.CommandType.StoredProcedure;
if (returnType != null)
{
com.Parameters.Add("ReturnValue", returnType.Value).Direction =
ParameterDirection.ReturnValue;
}
action(com);
}
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我也删除了includeReturn参数并returnType改为null为nullable.只需传递"无返回值".)
你将它与lambda表达式(或匿名方法)一起使用:
ExecuteSproc("SomeName", SqlDbType.DateTime, cmd =>
{
// Do what you want with the command (cmd) here
});
Run Code Online (Sandbox Code Playgroud)
这样处理与创建处于同一位置,并且调用者不需要担心它.我变得非常喜欢这种模式 - 现在我们已经有了lambda表达式,它已经变得更加清晰了.