【发布时间】:2009-01-12 16:39:26
【问题描述】:
最近我发现自己正在编写数据访问层选择方法,其中代码都采用这种通用形式:
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;
}
或者像这样:
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;
}
这些方法将由业务层代码调用,然后将基本 DataTable 或 DataRecord 转换为表示层可以使用的强类型业务对象。
由于我反复使用类似的代码,我想确保这段代码是最好的。那么如何改进呢?而且,是否值得尝试将通用代码从这里移到它自己的方法中。如果是这样,该方法会是什么样子(特别是关于传入 SqlParameter 集合)?
【问题讨论】:
-
你和我一样做这件事——虽然我真的很喜欢你如何堆叠你的双重 using 语句以避免深度嵌套。做得好!我感兴趣的一件事是你如何在逻辑上/物理上设置你的 DAL 与你的 BIZ - 你把它放在自己的项目中吗?或作为命名空间?还是什么?
-
如果没有参数,您也可以堆叠数据读取器。 DAL 在它自己的程序集中,DAL + BL 将共享一个公共父命名空间。
-
是的,我现在就是这样做的。您的业务对象和 DAL 对象之间的映射是什么?即你去 1:1 吗?我看到有趣的一件事是有人将 DAL 拉入业务对象并使用 CodeSmith 将其全部生成。很有趣
-
这不是 1:1,但这是这里系统的一个特点。我使用的数据库是来自大型机的快照转储,我们看到的表不是您所说的“通常”。
-
好的,但理想情况下,在您自己的规范化系统中,您会采用 1:1 的比例,您是否会像整合业务对象一样整合 dal 对象?即特定于一个业务对象的查找表 - 顺便说一句,这是一个很棒的话题,我也想在自己的工作中改进这一点
标签: .net .net-2.0 data-access-layer