Joe*_*orn 8 .net data-access-layer .net-2.0
最近我发现自己编写数据访问层选择方法,其中代码都采用这种通用形式:
public static DataTable GetSomeData( ... arguments)
{
string sql = " ... sql string here: often it's just a stored procedure name ... ";
DataTable result = new DataTable();
// GetOpenConnection() is a private method in the class:
// it manages the connection string and returns an open and ready connection
using (SqlConnection cn = GetOpenConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
// could be any number of parameters, each with a different type
cmd.Parameters.Add("@Param1", SqlDbType.VarChar, 50).Value = param1; //argument passed to function
using (SqlDataReader rdr = cmd.ExecuteReader())
{
result.Load(rdr);
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
或者像这样:
public static DataRow GetSomeSingleRecord( ... arguments)
{
string sql = " ... sql string here: often it's just a stored procedure name ... ";
DataTable dt = new DataTable();
// GetOpenConnection() is a private method in the class:
// it manages the connection string and returns an open and ready connection
using (SqlConnection cn = GetOpenConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
// could be any number of parameters, each with a different type
cmd.Parameters.Add("@Param1", SqlDbType.VarChar, 50).Value = param1; //argument passed to function
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
dt.Load(rdr);
}
}
if (dt.Rows.Count > 0)
return dt.Rows[0];
return null;
}
Run Code Online (Sandbox Code Playgroud)
这些方法将由业务层代码调用,然后将基础DataTable或DataRecord转换为表示层可以使用的强类型业务对象.
由于我反复使用类似的代码,我想确保这段代码是最好的.那又怎么改进呢?并且,是否值得尝试将公共代码从此移动到它自己的方法.如果是这样,该方法会是什么样的(特别是关于传递SqlParameter集合)?
我做的唯一不同的是我从自己的内部数据库帮助程序方法切换到实际的数据访问应用程序块http://msdn.microsoft.com/en-us/library/cc309504.aspx
使了解企业库的其他开发人员能够更加标准化/统一地学习代码。
| 归档时间: |
|
| 查看次数: |
10366 次 |
| 最近记录: |