最近我發現自己寫數據訪問層的選擇方法,其中的代碼全部採用一般形式:如何提高數據訪問層選擇方法模式
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語句,避免深度嵌套。做得好! 我感興趣的一件事是如何邏輯/ phyapan設置你的DAL與你的BIZ - 你把它放在它自己的項目?或者作爲一個命名空間?或者是什麼? – dfasdljkhfaskldjhfasklhf 2009-01-12 16:50:33
如果沒有參數,您也可以堆棧數據記錄器。 DAL在它自己的程序集中,DAL + BL將共享一個共同的父命名空間。 – 2009-01-12 16:53:29
是的,我現在怎麼做。業務對象和DAL對象之間的映射是什麼?即你去1:1?我看到有趣的一件事是將DAL拉入業務對象並使用CodeSmith生成全部內容。非常有趣 – dfasdljkhfaskldjhfasklhf 2009-01-12 16:59:31